john
john

Reputation: 707

How to find the cumulative value by group in mysql?

I have the following table

   id_val date_val    volume_val
    1   26-Jan-18   100
    1   25-Jan-18   200
    1   24-Jan-18   300
    1   23-Jan-18   150
    2   26-Jan-18   250
    2   25-Jan-18   350
    2   24-Jan-18   400
    3   23-Jan-18   500

I need to estimate the cumulative volume by id . This is what i want to get

id_val date_val    volume_val     cumulative_volume_val
1   26-Jan-18       100             100
1   25-Jan-18       200             300
1   24-Jan-18       300             600
1   23-Jan-18       150             750
2   26-Jan-18       250             250
2   25-Jan-18       350             600
2   24-Jan-18       400             1000
3   23-Jan-18       500             500

Here is what I tried but it doesnt work . it sums up everything and does not split by groups. How can I improve it ?

set @csum := 0;  

select id_val, date_val,   
(@csum := @csum + volume_val) as cumulative_volume      
from temp  
group by id_val, date_val    
order by id_val, date_val desc 

Upvotes: 0

Views: 49

Answers (1)

Mark Maurice Williams
Mark Maurice Williams

Reputation: 217

Here is a solution I adapted from the answer to a similar question here: Does mysql have the equivalent of Oracle's "analytic functions"?

select id_val, date_val,   
(case when @id_val != id_val then @sum := volume_val else @sum := @sum + volume_val end) as cumulative_volume,
(case when @id_val != id_val then @id_val := id_val else @id_val end) as _
FROM (SELECT * FROM temp ORDER BY id_val, date_val desc) z
JOIN (SELECT @sum := 0) s
JOIN (SELECT @idval := -1) i

Upvotes: 1

Related Questions