SQL-Postgres中的累积总和

时间:2018-11-23 12:49:04

标签: sql postgresql

我有这样的数据:

item - initial_value - amount - dateofpurchase 
A       100             -3      2018-11-22          
A       100             -2      2018-11-22      
B       200             -5      2018-11-22
B       200             6       2018-11-22
B       200             -1      2018-11-22

(一切都按日期和时间排序)

我想计算此列,该列显示每个步骤后您有多少库存并计入最后金额

item - initial_value - amount - dateofpurchase - cumulative
A       100             -3      2018-11-22          97
A       100             -2      2018-11-22          95
B       200             -5      2018-11-22          195
B       200             6       2018-11-22          201
B       200             -1      2018-11-22          200

我一直在尝试求和函数,其中前行和当前行无限制,没有运气

2 个答案:

答案 0 :(得分:1)

您可以使用窗口功能和减法:

select t.*,
       ( initial_amount +
         sum(amount) over (partition by item order by date_of_purchase)
       ) as cumulative
from t;

答案 1 :(得分:0)

使用窗口功能

with cte as
(
    select 'A' item, 100 as initial_value, -3 amount, '2018-11-22'::date as dateofpurchase
    union all
    select 'A' ,100, -2, '2018-11-22'
    union all
    select 'B',200, -5,'2018-11-22'
    union all
    select 'B',200, 6,'2018-11-22' 
    union all
    select 'B',200, -1,'2018-11-22' 
) 
,  t1 as
(select t.*, row_number() over(partition by item order by dateofpurchase) rn

from cte t
 ) 
 , t3 as
 (select *, case when rn=1 then initial_value else 0 end as val   from t1
  ) select item,initial_value,amount,dateofpurchase, sum(val+amount) over(partition by item order by rn) as cumulative  from t3

样本输出

item    initial_value   amount  dateofpurchase  cumulative
A          100          -3        2018-11-22    97
A          100          -2        2018-11-22    95
B          200          -5        2018-11-22    195
B          200           6        2018-11-22    201
B          200          -1        2018-11-22    200

demo link