我有以下数据集
month | spend
Jan | 100
Jan | 200
Feb | 10
Feb | 500
Feb | 100
March | 60
我希望每月汇总一次,如: -
Jan | 300
Feb | 910 // Spend till month of feb
March| 970 // Spend till month of March and so on...
我希望Sum明智地与前一个月的价值,我希望你理解。
答案 0 :(得分:1)
drop table if exists t;
create table t (month text, spend int);
insert into t values
("Jan", 100),
("Jan", 200),
("Feb", 10),
("Feb", 500),
("Feb", 100),
("March", 60);
select month, (@n:=@n + sum) sum
from
(select month, sum(spend) sum
from t
group by month
order by FIELD(MONTH,'Jan','Feb','March')
) t1
cross join
(select @n:=0) n
答案 1 :(得分:0)
如果您的实际月份名称被MySQL理解(请查看DATE_FORMAT()
),您也可以使用STR_TO_DATE('%b', month)
来确定月份的顺序。然后
SELECT t1.month, SUM(t2.spend)
FROM mytable t1
INNER JOIN mytable t2 ON STR_TO_DATE('%b', t2.month) <= STR_TO_DATE('%b', t1.month)
GROUP BY t1.month