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

一列的列转行
有一列列名aa
2007-01-01
2008-01-01
。。。。。
有几十列
如何变成一行的纪录,不要列名了

2007-01-01 2008-01-01 。。。。
select 语句中不出现纪录值2007-01-01,2008-01-01


------解决方案--------------------
SQL code
create table TB(aa varchar(10))
insert into TB values('2007-01-01') 
insert into TB values('2008-01-01')  
insert into TB values('2009-01-01')  
insert into TB values('2010-01-01')  
insert into TB values('2011-01-01')  
go
declare @sql varchar(8000)
set @sql = 'select id = 1'
select @sql = @sql + ' , max(case aa when null then aa else '' '' end) [' + aa + ']'
from (select distinct aa from tb) as a
set @sql = @sql + ' from (select id = 1 , * from tb) t group by id'
exec(@sql) 

drop table TB

/*
id          2007-01-01 2008-01-01 2009-01-01 2010-01-01 2011-01-01 
----------- ---------- ---------- ---------- ---------- ---------- 
1                                                        

*/