Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bounded Cumulative sum in Netezza

I know how to use cumulative sum in its basic formulation, with code like this:

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    

But how do I limit the cumulative sum to only N preceding rows? For example, limit cumulative sum to current row and previous two rows.

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    
like image 789
ADJ Avatar asked Oct 22 '25 21:10

ADJ


1 Answers

The SQL syntax is:

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;
like image 123
Gordon Linoff Avatar answered Oct 25 '25 11:10

Gordon Linoff