我似乎不知道如何聚合这个表。我需要从这个表中算出一个月总计的金额是多少。所以我有一些项目和每个项目的持续时间,每月平均收入(每个项目)。例如,我想查看 2011 年 5 月所有项目的总金额是多少。原始表格如下:
Year Month Amount Duration (month) average per month
2012 1 7 4 1.75
2012 2 6 5 1.2
2012 3 5 6 0.833333333
2012 4 4 6 0.666666667
2012 5 9 5 1.8
2012 6 10 4 2.5
2012 7 20 3 6.666666667
2011 4 13 2 6.5
2011 3 3 10 0.3
2011 12 4 11 0.363636364
2011 2 5 12 0.416666667
2011 3 7 3 2.333333333
2010 5 8 4 2
2010 7 3 6 0.5
2010 9 4 7 0.571428571
2010 11 5 8 0.625
2010 1 6 8 0.75
2010 2 7 8 0.875
2010 3 8 9 0.888888889
2010 4 9 1 9
如果有任何帮助,我将不胜感激。谢谢。
最佳答案
假设年份是 varchar ,月份/持续时间是 int (如果不是,您可能需要根据情况进行转换),您可以执行以下操作:
select sum(amount) from yourtable
where YearMonth between
period_add(year&'01',month-1) and period_add(year&'01',month+duration-2)
YearMonth 是一个带有要查询的年/月的字符串,在您的示例中为“201105”
对于若干年/月,您可以创建一个单列表:
create table yearmonths(yearmonth varchar(6));
insert into yearmonths values
('201101'),('201102'),(201103),
('201104'),('201105'),(201106)
并将其加入到您的表中:
Select yearmonth,sum(amount)
from yearmonths y
left join yourtable t
on(y.yearmonth between period_add(year&'01',month-1)and period_add(year&'01',month+duration-2)
group by yearmonth
关于mysql - 按月汇总金额列 - sql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25047147/