-1

考虑一个包含客户、排序日期和金额的表格,如下所示

User    Date    Purchase
Joe  '2020-01-01' 10
Joe  '2020-02-01' 20
Joe  '2020-02-20' 20
Joe  '2020-03-15' 15
Lucy '2020-01-12' 5
Lucy '2020-02-15' 30
Lucy '2020-02-21' 20
Lucy '2020-03-05' 30

我想获得一个新列,其中包含以前购买的累计花费,即

User    Date    Purchase Cum
Joe  '2020-01-01' 10      10
Joe  '2020-02-01' 20      30
Joe  '2020-02-20' 20      50
Joe  '2020-03-15' 15      65
Lucy '2020-01-12' 5        5
Lucy '2020-02-15' 30      35
Lucy '2020-02-21' 20      55
Lucy '2020-03-05' 30      85
4

3 回答 3

2

这将是:

select t.*,
       sum(purchase) over (partition by user order by date) as running_sum
from t;
于 2020-04-17T11:39:45.007 回答
1

您可以使用窗口功能:

sum(purchase) over (partition by user order by date) as purchase_sum

如果窗口函数不支持,那么您可以使用相关子查询:

select t.*,
       (select sum(t1.purchase) 
        from table t1 
        where t1.user = t.user and t1.date <= t.date 
       ) as purchase_sum
from table t;
于 2020-04-17T11:40:08.070 回答
1

尝试partition by

    Select  User, Date, Purchase, 
    sum(purchase ) 
    over (partition by User order by user )
     From table
于 2020-04-17T11:41:16.693 回答