【问题标题】:Mysql cumulative sum and group by month yearMysql累计总和和按月分组
【发布时间】:2018-03-07 15:05:06
【问题描述】:

我怎样才能使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

【问题讨论】:

标签: mysql group-by


【解决方案1】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-03
    • 2014-04-12
    • 1970-01-01
    • 2013-08-01
    • 1970-01-01
    • 2012-01-23
    • 2017-03-04
    相关资源
    最近更新 更多