我有一个这样的数据表:
RecID Name Value
1 Color Red
2 Size Small
3 Weight 20lbs
4 Shape Square
我需要一个将行作为列返回的查询,如下所示:
Color Size Weight Shape
Red Small 20lbs Square
SQL查询会是什么样的?我无法将任何值硬编码到查询中,只需要读取名称和值对并重新定向它们。
答案 0 :(得分:0)
测试数据
DECLARE @Table TABLE(RecID INT,Name VARCHAR(20),Value VARCHAR(20))
INSERT INTO @Table VALUES
(1,'Color' ,'Red'),
(2,'Size' ,'Small'),
(3,'Weight','20lbs'),
(4,'Shape' ,'Square')
<强>查询强>
SELECT *
FROM
(SELECT Name,Value
FROM @Table) T
PIVOT ( MAX(Value)
FOR Name
IN ([Color],[Size],[Weight],[Shape])
)P
结果集
╔═══════╦═══════╦════════╦════════╗
║ Color ║ Size ║ Weight ║ Shape ║
╠═══════╬═══════╬════════╬════════╣
║ Red ║ Small ║ 20lbs ║ Square ║
╚═══════╩═══════╩════════╩════════╝