日期:2014-05-17  浏览次数:20500 次

Sql 按月份分组
Table A(Name,Amount,Time)


想要的结果
Name,Mon,Feb....


其中,Mon/Feb/...显示按照月份的Sum(Amount)


求大牛指导。
sql

------解决方案--------------------
select name,[mon]=sum(case when month(time)=1 then amount else 0 end ),
[feb]=sum(case when month(time)=2 then amount else 0 end )..12个月自己补全
from a
group by name
------解决方案--------------------

--如果不是2008以上版本,用这个
select name,[mon]=sum(case when CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(30),[time],23),6,2))=1 then amount else 0 end ),
[feb]=sum(case when CONVERT(INT,SUBSTRING(CONVERT(VARCHAR(30),[time],23),6,2))=2 then amount else 0 end )..12个月自己补全
from a
group by name
------解决方案--------------------
create table tableA(Name varchar(10),Amount numeric(12,2),[time] date) 
insert into tableA
select 'Tommy',100,'2012-1-10'
union all select 'Tommy',101,'2012-2-11'
union all select 'Tommy',102,'2012-8-12'
union all select 'Tommy',103,'2012-4-13'
union all select 'Tommy',104,'2012-10-14'
union all select 'Jenny',105,'2012-6-15'
union all select 'Jenny',106,'2012-3-16'
union all select 'Jenny',107,'2012-8-17'
union all select 'Jenny',108,'2012-9-18'
union all select 'Jenny',109,'2012-5-19'
union all select 'Jenny',110,'2012-11-20'
union all select 'Jenny',111,'2012-12-21'

declare @groupField varchar(1000)
select @groupField=isnull(@groupField,'')+case when isnull(@groupField,'')='' then '' else ',' end+QUOTENAME(YM) 
from (select distinct CONVERT(varchar(7),[time],120) as YM from tableA)t
declare @sql nvarchar(4000)
set @sql=N'select *
from 
(select Name, CONVERT(varchar(7),[time],120) YM,sum(Amount) as Amount