在sql中将行转换为列

时间:2015-05-21 07:33:51

标签: sql sql-server-2014 unpivot

我有这样的表:

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 server 2014。

1 个答案:

答案 0 :(得分:1)

如果您考虑此表和这些测试值:

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中看到它。