sql按月求和语句怎么写

2024-12-04 20:57:15
推荐回答(5个)
回答1:

使用 case when 配合 sum来统计。

如图表a2

语句如下: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;

运行结果:

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

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


回答2:

select year(trandate) * 100 + month(trandate) as trandate, sum(tranamount) as tranamount
from normaltran
group by year(trandate) * 100 + month(trandate)
结果:
200801 140
200802 45
。。。
如果一定要 2008-01这种格式也可以,作相应的就该就行。
cast(year(trandate) as varchar(5)) + '-' + cast(month(trandate) as varchar(2))

回答3:

给你个思路 :
08年一月份:
select sum(tranamount) from normaltran where year(trandate)='2008' and month(trandate)='1'and day(trandate)>0 and day(trandate)<32

我推荐wangzhiqing999的 很好

回答4:

SELECT
CAST(YEAR(trandate) as varchar) + '-' + CAST(MONTH(trandate) as varchar) AS trandate ,
SUM( tranamount ) AS tranamount
FROM
normaltran
GROUP BY
CAST(YEAR(trandate) as varchar) + '-' + CAST(MONTH(trandate) as varchar)

回答5:

select CONVERT(VARCHAR(6),trandate,111) as trandate,sum(tranamount) as tranamount
from normaltran
group by CONVERT(VARCHAR(6),trandate,111)