问题:计算某个列中所有值的累计和。
解决方案:下面给出了一种解决方案,它展示 了如何计算所有职员工资的累计和。为了增加可读性,其结果是按SAL排序的,这样就能够很容易地观察到累计和变化的过程。
select e.ename,e.sal,
(select sum(d.sal) from emp d
where d.empno<=e.empno) as running_total
from emp e
order by 3;
+--------+------+---------------+
| ename | sal | running_total |
+--------+------+---------------+
| ALLEN | 1600 | 1600 |
| WARD | 1250 | 2850 |
| MARTIN | 1250 | 4100 |
| BLAKE | 2850 | 6950 |
| CLARK | 2450 | 9400 |
| KING | 5000 | 14400 |
| TURNER | 1500 | 15900 |
| JAMES | 950 | 16850 |
| MILLER | 1300 | 18150 |
+--------+------+---------------+