Mysql累计总和和逐月组

时间:2018-03-07 15:05:07

标签: mysql group-by

如何按月份生成mysql列和组的累积总和 这是我的表"保存"

id date         value
1  01/01/2018   10
2  01/12/2018   5
3  02/03/2018   6
4  02/23/2018   4

我尝试这个查询

SET @SumVariable:=0;
select CONCAT(LEFT(monthname(date),3),'-', year(date)) as month
    ,sum(value)
    ,(@SumVariable := @SumVariable + sum(value)) AS total
FROM saving
GROUP BY year(date), month(date) LIMIT 50

查询返回

month      value
jan-2018    15
feb-2018    10

它不是累积总和,我需要输出如下

month       total
jan-2018    15
feb-2018    25

1 个答案:

答案 0 :(得分:0)

试试这个:

select date_format(s1.date,'%b-%Y') as month,
       (select sum(s2.value) 
        from saving s2 
        where s2.date <= last_day(s1.date)) as total
from saving s1
group by month
order by s1.date
limit 50;

您可以看到有关此问题的更多信息:

Create a Cumulative Sum Column in MySQL