在sql中将列反转为行标题

在sql中将列反转为行标题,sql,sql-server-2005,tsql,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

我有一张桌子

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
这是否可以使用pivot或任何其他方法实现

我们正在使用SQL2005 谢谢

剧本

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' 

对于IPHONE:

DECLARE @result VARCHAR(MAX) = 'IPHONE '

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

SELECT @result
如果使用光标并选择所有不同的productCode,您可以轻松地为所有…

IPHONE执行此操作:

DECLARE @result VARCHAR(MAX) = 'IPHONE '

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

SELECT @result

如果使用游标并选择所有不同的productCode,则可以轻松地对所有…

执行此操作。如果属性名称不断更改或不是静态的,则可以使用此选项

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)

如果属性名称不断更改或不是静态的,则可以使用

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)

是的,你可以用Pivot来做这个。属性是固定列表吗?如果不是,则需要动态SQL。是否在属性后面显示为列以及值,因此输出中有7列?Martin-属性列表不是固定的。网络猕猴桃-是的。必须使用动态sql来获取它。是的,您可以使用Pivot来实现这一点。属性是固定列表吗?如果不是,则需要动态SQL。是否在属性后面显示为列以及值,因此输出中有7列?Martin-属性列表不是固定的。网络猕猴桃-是的。必须使用动态sql才能获得它。谢谢。Pivot解决方案都不起作用。必须使用动态查询。必须调整查询以获得结果。谢谢。Pivot解决方案均无效。必须使用动态查询。必须调整查询以获得结果。