行列转换
1、行转换成列:
if object_id('tablename')is not null drop table tablename
select 'x1'as [name], '2006-01-01' as [date], 'aaaa' as nr
into tablename
union select 'x1', '2006-01-02', 'bbbb'
union select 'x3', '2006-01-03', 'dddd'
select * from tablename
-----------------------------------------------------
declare @s varchar(2000)
set @s = 'select [name]'
select @s = @s + ', min(case when [date] = ''' + [date] + ''' then nr end) as [' + [date] + ']'
from (select distinct[date] from tablename) a
set @s = @s + ' from tablename group by [name]'
exec(@s)
if object_id('tablename')is not null drop table tablename
select 'x1'as [name], '2006-01-01' as [date], 'aaaa' as nr
into tablename
union select 'x1', '2006-01-02', 'bbbb'
union select 'x3', '2006-01-03', 'dddd'
select * from tablename
-----------------------------------------------------
declare @s varchar(2000)
set @s = 'select [name]'
select @s = @s + ', min(case when [date] = ''' + [date] + ''' then nr end) as [' + [date] + ']'
from (select distinct[date] from tablename) a
set @s = @s + ' from tablename group by [name]'
exec(@s)