经典转换问题,散分了 !
当前数据:
AID Aname IsOpen1 IsOpen2 CS1 CS2
1F3C 黄浦 0 1 家乐福 沃尔玛
27B9 徐汇 1 0 家乐福 沃尔玛
30AF 卢湾 1 1 家乐福 沃尔玛
AID Aname 家乐福 沃尔玛
1F3C 黄浦 0 1
27B9 徐汇 1 0
30AF 卢湾 1 1
create table lee
(AID varchar(10), Aname varchar(10),
IsOpen1 int, IsOpen2 int,
CS1 varchar(10), CS2 varchar(10))
insert into lee
select '1F3C', '黄浦', 0, 1, '家乐福', '沃尔玛' union all
select '27B9', '徐汇', 1, 0, '家乐福', '沃尔玛' union all
select '30AF', '卢湾', 1, 1, '家乐福', '沃尔玛'
select AID,Aname,[家乐福],[沃尔玛]
from
(select AID,Aname,CS1 'CS',IsOpen1 'IsOpen' from lee
union all
select AID,Aname,CS2 'CS',IsOpen2 'IsOpen' from lee) t
pivot(max(IsOpen) for CS in([家乐福],[沃尔玛])) p
/*
AID Aname 家乐福 沃尔玛
---------- ---------- ----------- -----------
1F3C 黄浦 0 1
30AF 卢湾 1 1
27B9 徐汇 1 0
(3 row(s) affected)
*/
create table lee
(AID varchar(10), Aname varchar(10),
IsOpen1 int, IsOpen2 int,
CS1 varchar(10), CS2 varchar(10))
insert into lee
select '1F3C', '黄浦', 0, 1, '家乐福', '沃尔玛' union all
select '27B9', '徐汇', 1, 0, '家乐福', '沃尔玛' union all
select '30AF', '卢湾', 1, 1, '家乐福', '沃尔玛'
declare @tsql varchar(6000)
select @tsql='select AID,Aname,'
+'IsOpen1 '''+(select top 1 CS1 from lee)+''','
+'IsOpen2 '''+(select top 1 CS2 from lee)+''' '
+' from lee '
exec(@tsql)
/*
AID Aname 家乐福 沃尔玛
---------- ---------- ----------- -----------
1F3C 黄浦 0 1
27B9 徐汇 1 0
30AF 卢湾 1 1
(3 row(s) affected)
*/