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

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


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


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


求大牛指导。
------解决方案--------------------
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   
from tableA 
group by Name,CONVERT(varchar(7),[time],120)
) as x
pivot (sum(Amount)for YM in ('+@groupField+')) as pvt
order by Name'
EXEC (@sql)

drop table tableA

/*
Name 2012-01 2012-02 2012-03 2012-04 2012-05 2012-06 2012-08 2012-09 2012-10 2012-11 2012-12
---------------------------------------------------------------------------------------------------
Jenny NULL NULL 106.00 NULL 109.00 105.00 107.00 108.00 NULL 110.00 111.00
Tommy 100.00 101.00 NULL 103.00 NULL NULL 102.00 NULL 104.00 NULL NULL
*/

------解决方案--------------------
上面少了7月份数据,如果有7月数据它会自动跑出来。
你是否想要没有数据的月份也出来?