日期:2014-05-18  浏览次数:20645 次

数据分类汇总问题?
测试数据:
create table #table(id int,y_month char(7),num int)
insert into #table values(0,'2009-12',519),
(0,'2009-2',463),
(0,'2009-9',723),
(0,'2010-1',199),
(0,'2010-8',371),
(0,'2011-1',278),
(0,'2011-12',437),
(0,'2011-2',441),
(1,'2009-1',370),
(1,'2009-9',230),
(1,'2010-1',247),
(1,'2011-11',821),
(2,'2009-1',836),
(2,'2010-8',416),
(2,'2011-9',799);

问题:
统计每年的每个月的num数值?
结果形式:(id=2的部分) 要求:对同一个id,月份不能重复。
id 月份 [2009] [2010] [2011] 
2 1 836 NULL NULL
2 2 NULL NULL NULL
2 3 NULL NULL NULL
. . . . .
. . . . .
. . . . .
2 8 NULL 416 NULL
2 9 NULL NULL 799
2 10 NULL NULL NULL
. . . . .

------解决方案--------------------
稍微调整了一下,试试看
SQL code

declare @table table(id int,y_month datetime,num int)
insert into @table 
select 0,'2009-12-1',519 union all
select 0,'2009-2-1',463 union all
select 0,'2009-9-1',723 union all
select 0,'2010-1-1',199 union all
select 0,'2010-8-1',371 union all
select 0,'2011-1-1',278 union all
select 0,'2011-12-1',437 union all
select 0,'2011-2-1',441 union all
select 1,'2009-1-1',370 union all
select 1,'2009-9-1',230 union all
select 1,'2010-1-1',247 union all
select 1,'2011-11-1',821 union all
select 2,'2009-1-1',836 union all
select 2,'2010-8-1',416 union all
select 2,'2011-9-1',799 

select 
id, 
datepart(month,y_month) month,
sum(case when datepart(year,y_month) = 2009 then num else 0 end) as '2009',
sum(case when datepart(year,y_month) = 2010 then num else 0 end) as '2010',
sum(case when datepart(year,y_month) = 2011 then num else 0 end) as '2011'
from @table
group by
id, 
datepart(month,y_month)
order by
id,
datepart(month,y_month)

------解决方案--------------------
sum汇总一下就好了