日期:2014-05-17  浏览次数:20504 次

求MSSQL列转行语句
这个看起来似乎比较难.

查询的结果是
GroupName Price
-------------------------------------------------- ---------------------
VIP客户 1011.00
白金卡会员 225.00

(2 行受影响)

要转成
VIP客户 白金卡会员 
1011.00 225.00

有没有人指导下.不胜感激!

------解决方案--------------------
SQL code
CREATE TABLE tb (GroupName VARCHAR(64),Price decimal(10,2))
INSERT INTO tb
SELECT 'VIP客户',1011.00 
UNION ALL
SELECT'白金卡会员',225.00
UNION ALL
SELECT'白金卡会员1',225.00
UNION ALL
SELECT'白金卡会员2',225.00
UNION ALL
SELECT'白金卡会员3',225.00
UNION ALL
SELECT'白金卡会员4',225.00
UNION ALL
SELECT'白金卡会员4',225.00


--DROP TABLE tb
declare @s nvarchar(max)
set @s=''
Select     @s=@s+','+quotename(GroupName)+'=max(case when [GroupName]='+quotename(GroupName,'''')+' then [price] else 0 end)'
from tb group by GroupName
SELECT @s=SUBSTRING(@s,2,LEN(@s))

EXEC ('select '+@s+' from tb ')

/*
VIP客户                                   白金卡会员                                   白金卡会员1                                  白金卡会员2                                  白金卡会员3                                  白金卡会员4
--------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- --------------------------------------- ---------------------------------------
1011.00                                 225.00                                  225.00                                  225.00                                  225.00                                  225.00

(1 行受影响)


*/