如何在mysql中按组查找累积值?

时间:2018-01-28 04:16:44

标签: mysql

我有下表

   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

我需要通过id估算累积量。这就是我想要的

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

这是我尝试的但它不起作用。它总结了一切,并没有按群体分割。我怎样才能改进它?

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 

1 个答案:

答案 0 :(得分:1)

以下是我根据类似问题的答案改编的解决方案: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