Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Cumulative sum in a partition by

Consider a table with customers, sorted dates and amounts as follows

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

I would like to obtain a new column with the cumulative spent with the previous purchases, i.e.,

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
like image 427
simon Avatar asked Aug 31 '25 10:08

simon


2 Answers

This would be:

select t.*,
       sum(purchase) over (partition by user order by date) as running_sum
from t;
like image 123
Gordon Linoff Avatar answered Sep 03 '25 07:09

Gordon Linoff


You can use window function :

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

if window function not supports then you can use correlated subquery :

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;
like image 28
Yogesh Sharma Avatar answered Sep 03 '25 07:09

Yogesh Sharma