sql按月求和语句怎么写
表normaltrantrandatetranamount2008-01-01502008-01-15802008-02-13452009-05-15602009-05-...
表normaltran
trandate tranamount
2008-01-01 50
2008-01-15 80
2008-02-13 45
2009-05-15 60
2009-05-16 35
2009-05-25 66
想得到最终结果为
trandate tranamount
2008-01 140
2008-02 45
2008-05 95
。。。。。。。。。。
请问sql语句该怎么写呀 展开
trandate tranamount
2008-01-01 50
2008-01-15 80
2008-02-13 45
2009-05-15 60
2009-05-16 35
2009-05-25 66
想得到最终结果为
trandate tranamount
2008-01 140
2008-02 45
2008-05 95
。。。。。。。。。。
请问sql语句该怎么写呀 展开
2015-12-05 · 知道合伙人软件行家
关注
展开全部
使用 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);
展开全部
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))
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))
追问
如果表中还有一列mchntid
1
2
3
。。。。。。
结果:
1 200801 140
2 200802 45
mchntid 写在哪?
追答
这有个问题:2008年1月有两条记录,选择记录的mchntid 呢?
如果选择每组最小的mchntid ,可以用聚合函数 min(mchntid).
如下:
select min(mchntid) as mchntid , year(trandate) * 100 + month(trandate) as trandate, sum(tranamount) as tranamount
from normaltran
group by year(trandate) * 100 + month(trandate)
本回答被提问者和网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
给你个思路 :
08年一月份:
select sum(tranamount) from normaltran where year(trandate)='2008' and month(trandate)='1'and day(trandate)>0 and day(trandate)<32
我推荐wangzhiqing999的 很好
08年一月份:
select sum(tranamount) from normaltran where year(trandate)='2008' and month(trandate)='1'and day(trandate)>0 and day(trandate)<32
我推荐wangzhiqing999的 很好
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
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)
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)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
select CONVERT(VARCHAR(6),trandate,111) as trandate,sum(tranamount) as tranamount
from normaltran
group by CONVERT(VARCHAR(6),trandate,111)
from normaltran
group by CONVERT(VARCHAR(6),trandate,111)
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询