Cumulative Sum per item in DB2

2019-08-27 14:35发布

问题:

I have DB2 table like below -

Date1       Item_code    Amt
2018-06-01  1            2
2018-06-02  1            3
2018-06-03  2            4
2018-06-03  2            5
2018-06-04  3            6
2018-06-05  3            7
2018-06-06  4            8

I need the cumulative sum item_code wise per day. The result should look like -

Date1       Item_code    Amt
2018-06-01  1            2
2018-06-02  1            5
2018-06-03  2            9
2018-06-04  3            6
2018-06-05  3            13
2018-06-06  4            8

I have tried a lot by myself and search also on SO but nothing is fulfilling my need. There are a lot of examples if I just need the cumulative sum day wise irrespective of item code.

Any help is greatly appreciated. Thanks in advance.

回答1:

I think you want aggregation with a cumulative sum:

select item_code, date1,
       sum(sum(amt)) over (partition by item_code order by date1) as running_amt
from t
group by item_code, date;


标签: sql db2