在 sql 中将行转换为列

Transform row to column in sql

我有 table 这样的:

PC(code, model, speed, ram, hd, cd, price)

当我 运行 查询时:

select model,speed,ram,hd,cd,price from PC where code=(select max(code) from PC) 我得到如下结果:

model   speed   ram   hd    cd     price
1233    800     128  20.0   50x  970.0000

但我需要使用 unpivot:

的结果
chr    value
cd      50x
hd      20
model   1233
price   970.00
ram     128
speed   800

我正在使用 sql 服务器 2014。

如果您考虑这个 table 和这些测试值:

DECLARE @tbl TABLE(model INT,speed INT,ram INT,hd FLOAT,cd VARCHAR(10),price FLOAT)
INSERT INTO @tbl
VALUES
(1233,800,128,20.0,'50x',970.0000)

你可以这样做:

SELECT
    unpvt.chr,
    unpvt.value
FROM
(
    SELECT 
        CAST(model AS VARCHAR(10)) AS model,
        CAST(speed AS VARCHAR(10)) AS speed,
        CAST(ram AS VARCHAR(10)) AS ram,
        CAST(hd AS VARCHAR(10)) AS hd,
        cd,
        CAST(price AS VARCHAR(10)) AS price
    FROM 
        @tbl AS t
) AS sourceTable
UNPIVOT
(
    value 
    FOR chr IN(model,speed,ram,hd,cd,price)
)
AS unpvt
ORDER BY unpvt.chr

这将导致此输出:

chr     value
---------------
cd      50x
hd      20
model   1233
price   970
ram     128
speed   800

你可以在这个SQLFIDDLE中看到它。