110,537
社区成员
发帖
与我相关
我的任务
分享
drop table tb
go
create table tb(a varchar(20),b varchar(20),c varchar(20),d varchar(20))
insert into tb select '1','2','3','4'
insert into tb select '5','6','7','8'
declare @i int,@sqlresult varchar(8000)
set @sqlresult=''
set @i=1
while @i<=(select count(1) from syscolumns where id=object_id('tb'))
begin
declare @sql varchar(8000),@colname varchar(50)
select @colname=name from syscolumns where id=object_id('tb') and colid=@i
select @sql=isnull(@sql+',','')+' max(case when id='''+ltrim(id)+''' then '+@colname+' end) as [第'+ltrim(id)+'列]'
from(select row_number() over(order by a) as id,* from (select * from tb union all select 'a','b','c','d')t)t
set @sql='select '+@sql+' from (select row_number() over(order by a) as id,* from (select * from tb union all select ''a'',''b'',''c'',''d'')t)t union all '
set @sqlresult=@sqlresult+@sql
set @sql=null
set @i=@i+1
end
set @sqlresult = left (@sqlresult,len(@sqlresult)-10)
exec(@sqlresult)
create table tb(a varchar(20),b varchar(20),c varchar(20),d varchar(20))
insert into tb select '1','2','3','4'
insert into tb select 'a','b','c','d'
select max(case when id='1' then a end) as [1],max(case when id='2' then a end) as [2] from (select row_number() over(order by a) as id,* from tb)t
union all
select max(case when id='1' then b end) as [1],max(case when id='2' then b end) as [2] from (select row_number() over(order by a) as id,* from tb)t
union all
select max(case when id='1' then c end) as [1],max(case when id='2' then c end) as [2] from (select row_number() over(order by a) as id,* from tb)t
union all
select max(case when id='1' then d end) as [1],max(case when id='2' then d end) as [2] from (select row_number() over(order by a) as id,* from tb)t
create table tb(a int,b int,c int,d int)
insert into tb select 1,2,3,4
insert into tb select 5,6,7,8
select max(case when id='1' then a end) as [1],max(case when id='2' then a end) as [2] from (select row_number() over(order by a) as id,* from tb)t
union all
select max(case when id='1' then b end) as [1],max(case when id='2' then b end) as [2] from (select row_number() over(order by a) as id,* from tb)t
union all
select max(case when id='1' then c end) as [1],max(case when id='2' then c end) as [2] from (select row_number() over(order by a) as id,* from tb)t
union all
select max(case when id='1' then d end) as [1],max(case when id='2' then d end) as [2] from (select row_number() over(order by a) as id,* from tb)t