如何将一列数据以月份按行显示1
原帖已完结,http://bbs.csdn.net/topics/390560533
hdhai9451,你好,帮我再改改了 我加完条件后出现数据不对,如下
create table #tb([date] datetime,[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(convert(varchar(7),[date],120))+']=sum(case convert(varchar(7),[date],120) when '''+rtrim(convert(varchar(7),[date],120))+''' then s1 end)'
from #tb where [date]='2013-1-16' group by [date]
exec('select name'+@sql+'from #tb group by name' )
drop table #tb
name 2013-01
a 5
b 2
c NULL
create table #tb([date] datetime,[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(convert(varchar(7),[date],120))+']=sum(case convert(varchar(7),[date],120) when '''+rtrim(convert(varchar(7),[date],120))+''' then s1 end)'
from #tb where [date]='2013-1-16' group by [date]
exec('select name'+@sql+'from #tb where [date]=''2013-1-16'' group by name' ) ---这里也要加条件