2015-05-21 61 views
0

我的表是這樣的:變換排列在SQL

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

+0

你使用的是什麼版本的sql? mysql,sqlserver,oracle? –

+0

sql server 2014 @JeremyC。 – sajju217

+0

你已經標記了答案 - UNPIVOT。請參閱:http://www.sqlservercurry.com/2011/01/unpivot-example-in-sql-server.html – CeOnSql

回答

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