日期:2014-05-17 浏览次数:20701 次
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
*/