在SQL中将列反转为行标题

时间:2011-01-12 22:06:05

标签: sql sql-server-2005 tsql

我有一张桌子

ID  Productcode  AttName    Attval
1   IPHONE       Color  Black
2   IPHONE       Bluetooth  Yes
3   IPHONE       Camera Yes
4   MOTV         Color  Silver
5   MOTV         Bluetooth  No
6   MOTV         Camera No

我需要生成

IPHONE  Color   Black   Bluetooth   Yes Camera  Yes
MOTV    Color   Silver  Bluetooth   No  Camera  No

这可以使用枢轴或任何其他方法吗?

我们正在使用sql 2005 感谢

脚本

Create TAble TempInve(ID INT Identity(1,1),Productcode VARCHAR(40),AttName VARCHAR(40),Attval VARCHAR(50))
INSERT INTO TempInve
SELECT 'IPHONE','Color','Black' UNION ALL 
SELECT 'IPHONE','Bluetooth','Yes' UNION ALL
SELECT 'IPHONE','Camera','Yes' 


INSERT INTO TempInve
SELECT 'MOTV','Color','Silver' UNION ALL 
SELECT 'MOTV','Bluetooth','No' UNION ALL
SELECT 'MOTV','Camera','No' 

3 个答案:

答案 0 :(得分:2)

SELECT Productcode, 
       MAX(CASE WHEN AttName='Color' THEN Attval END) AS Attval,
       MAX(CASE WHEN AttName='Bluetooth' THEN Attval END) AS Bluetooth,
       MAX(CASE WHEN AttName='Camera' THEN Attval END) AS Camera
FROM TempInve
GROUP BY Productcode

或者

;WITH T
     AS (SELECT Productcode,
                AttName,
                Attval
         FROM   TempInve)
SELECT *
FROM   T PIVOT( max (Attval) FOR AttName IN ( [Color], [Bluetooth], [Camera] ) )
       AS pvt  

答案 1 :(得分:2)

对于IPHONE:

DECLARE @result VARCHAR(MAX) = 'IPHONE '

SELECT @result += AttName + ' ' + Attval + ' '
FROM TempInve
WHERE productCode = 'IPHONE'

SELECT @result

如果您使用光标并选择所有不同的productCode,您可以轻松地为所有人...

执行此操作

答案 2 :(得分:1)

如果您的属性名称不断变化或不是静态的,那么您可以使用此

declare @sql nvarchar(max);

-- generate the column names
select @sql = coalesce(@sql + ',', '') + QuoteName(AttName)
from (select distinct AttName from TempInve) T;

-- replace the column names into the generic PIVOT form
set @sql = REPLACE('
select ProductCode, :columns:
from (select Productcode, AttName, Attval From TempInve) p
pivot (max(attval) for attname in (:columns:)) pv',
':columns:', @sql)

-- execute for the results
exec (@sql)