如何在MySQL中计算反向运行总和

问题描述 投票:0回答:1

我有这个查询,在这里我计算了累加和。现在,我需要为同一变量计算反向累计和]

SELECT t1.date, t1.ant, t1.hab,  
(@csum:= @csum + t1.hab) as cumulative_hab
from(
SELECT date,
        ant, 
        sum(num_habit) as hab
        from xxxxxxxxxx
        WHERE date BETWEEN CURDATE() - INTERVAL 5 DAY AND CURDATE()
        group by ant) AS t1
,(select @csum := 0) vars
order by t1.ant

我的桌子看起来像这样

date       ant   hab    cumulative_hab
24-05-2020  0   382,000   382,000
24-05-2020  1   28,000    410,000
24-05-2020  2   26,000    436,000
24-05-2020  3   11,000    447,000
24-05-2020  4   29,000    476,000
24-05-2020  6   6,000     482,000
24-05-2020  7   12,000    494,000
28-05-2020  8   50,000    544,000
24-05-2020  12  5,000     549,000
24-05-2020  13  6,000     555,000

我希望另一列具有反向运行总和(反向累积总和,计算出第一个值555-382

 date      ant   hab    cumulative_hab   reverse_cum_hab
24-05-2020  0   382,000   382,000             555,000
24-05-2020  1   28,000    410,000             173,000, 
24-05-2020  2   26,000    436,000             145,000
24-05-2020  3   11,000    447,000             119,000
24-05-2020  4   29,000    476,000             108,000
24-05-2020  6   6,000     482,000              79,000
24-05-2020  7   12,000    494,000              73,000
28-05-2020  8   50,000    544,000              61,000
24-05-2020  12  5,000     549,000              11,000
24-05-2020  13  6,000     555,000               6,000
mysql
1个回答
1
投票
作为入门:如果您正在运行MySQL 8.0,则可以通过窗口函数轻松地做到这一点:

select date, ant, sum(num_habit) as hab, sum(sum(num_habit)) over(order by date) cumulative_hab, sum(sum(num_habit)) over(order by date desc) reverse_cumulative_hab from mytable where date between current_date - interval 5 day and current_date group by date, ant

在早期版本中,它更加复杂。我建议加入两个查询:

select t.*, r.reverse_cumulative_hab from ( select t.*, @csum := @csum + hab cumulative_hab from ( select date, ant, sum(num_habit) as hab from mytable where date between current_date - interval 5 day and current_date group by date, ant order by date ) t cross join (select @csum := 0) x ) t inner join ( select t.*, @rcsum := @rcsum + hab reverse_cumulative_hab from ( select date, ant, sum(num_habit) as hab from mytable where date between current_date - interval 5 day and current_date group by date, ant order by date desc ) t cross join (select @rcsum := 0) x ) r on r.date = t.date and r.can = s.can

© www.soinside.com 2019 - 2024. All rights reserved.