查看SUM Analytic Function中的Oracle Base并运行期望SUM的SQL会一次添加一行工资。
SELECT
deptno,
ename,
sal,
SUM(sal)
OVER (
PARTITION BY deptno
ORDER BY sal
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
)
AS RUNNING_TOTAL_IN_DEPT
FROM
emp
ORDER BY deptno, sal
;
但是,对于具有相同工资值的行,会添加具有相同工资值的行的子总数。
DEPTNO ENAME SAL RUNNING_TOTAL_IN_DEPT
20 SMITH 800 800
20 ADAMS 1100 1900
20 JONES 2975 4875
20 SCOTT 3000 10875 <--- Why not 7875? How to make this to 7875?
20 FORD 3000 10875
30 JAMES 950 950
30 MARTIN 1250 3450 <--- Why not 2200?
30 WARD 1250 3450
30 TURNER 1500 4950
30 ALLEN 1600 6550
请解释此行为,以及如果有多行具有相同的工资值,如何一次添加一行总和。
答案 0 :(得分:5)
您使用的是RANGE BETWEEN
而不是ROWS BETWEEN
。 RANGE BETWEEN
将具有相同键值的所有行视为相同,因此它们都获得“完整”值。
Oracle文档无法解释这一点。 Here是一篇博客文章,提供了一些背景资料。
答案 1 :(得分:2)
您希望ROWS BETWEEN
代替RANGE BETWEEN
:
SELECT deptno, ename, sal,
SUM(sal) OVER (PARTITION BY deptno ORDER BY sal
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RUNNING_TOTAL_IN_DEPT
FROM emp
ORDER BY deptno, sal;