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

如何将一列数据以月份按行显示
如题,例如:
表 test
date          name     sl
2013-1-5       a         3
2013-1-15      b         2
2013-1-16      a         2
2013-2-5       a         1
2013-2-5       b         1
2013-3-5       b         1
2013-3-5       c         5
....        

如何让她最终显示:
name   2013-1   2013-2   2013-3   .....(如有月份继续增加)
a        5         1        0
b        2         1        1
c        0         0        5
.....

SQL

------解决方案--------------------
create table #tb([date] varchar(10),[name] varchar(10),s1 int)
insert into #tb
select '2013-1-5' as [date],'a' as [name],3 as s1
union all select '2013-1-15','b',2
union all select '2013-1-16','a',2
union all select '2013-2-5','a',1
union all select '2013-2-5','b',1
union all select '2013-3-5','b',1
union all select '2013-3-5','c',5

select * from #tb

declare @sql varchar(8000)
set @sql=''
select @sql=@sql + ',['+rtrim([date])+']=max(case [date] when '''+rtrim([date])+''' then s1 end)'
from #tb group by [date]