我知道如何在其基本公式中使用累积和,代码如下:
Table Name: Employees
dept_id salary
-------------
10 1000
10 1000
10 2000
10 3000
20 5000
20 6000
20 NULL
SELECT dept_id,
salary,
SUM(salary) OVER(PARTITION BY dept_id
ORDER BY salary ASC
rows unbounded preceding) cum_sum
FROM Employees;
dept_id salary cum_sum
--------------------------
10 1000 1000
10 1000 2000
10 2000 4000
10 3000 7000
20 5000 5000
20 6000 11000
20 NULL 11000
但是如何将累积总和限制为仅前N行? 例如,将累积和限制为当前行和前两行。
dept_id salary cum_sum
--------------------------
10 1000 1000
10 1000 2000
10 2000 4000
10 3000 6000
20 5000 5000
20 6000 11000
20 NULL 11000
答案 0 :(得分:5)
SQL语法是:
SELECT dept_id,
salary,
SUM(salary) OVER(PARTITION BY dept_id
ORDER BY salary ASC
rows between <N> preceding and current row) cum_sum
FROM Employees;