使用 case when 配合 sum来统计。

如图表a2

sql按月求和语句_sql按月求和语句

语句如下:sum部分大意:当时间在区间内sl参加SUM计算,否则sl以0参加SUM计算

select 
sum(case when rq >='2015-1-1' and rq < '2015-2-1' then sl else 0 end) as '1月份',
sum(case when rq >='2015-2-1' and rq < '2015-3-1' then sl else 0 end) as '2月份',
sum(case when rq >='2015-3-1' and rq < '2015-4-1' then sl else 0 end) as '3月份' 
from a2;

运行结果:sql按月求和语句_sql按月求和语句_02

以列方式统计,更为简单:把rq 转换为年+月 格式,再分组即可以。

select year(rq) * 100 + month(rq) as rq, sum(sl) as 'sl' 
from a2
group by year(rq) * 100 + month(rq);

sql按月求和语句_sql按月求和语句_03