2013-08-24 103 views
1

如果我將不得不例如在一些表:透視逆透視其他欄

[Speed] [Ram] [Whatever] [Other] 
     S1 R1  W1  O1 
     S2 R2  W2  O2 
     S3 R3  W3  O3 

而且我想都這樣。

[Chr]  [Value] 
Speed  S3 
Ram  R3 
Whatever W3 
Other  O3 

所以我寫下面的代碼:

SELECT value 
FROM 
    (SELECT speed, ram 
    FROM pc where code=3) p 
UNPIVOT 
    (value FOR xxx IN 
     (speed, ram) 
)AS unpvt 

問題是,當我想補充我的第二列[CHR]

SELECT value, chr <---- This does not work 
     FROM 
      (SELECT speed, ram, whatever, other 
      FROM pc where code=3) p 
     UNPIVOT 
      (value FOR xxx IN 
       (speed, ram) 
     )AS unpvt 
UNPIVOT 
      (chr FOR zzz IN 
       (speed, ram, whatever, other) 
     )AS unpvt 

我不知道怎麼加此代碼的另一列。請任何建議。

+1

不太清楚你的要求。爲什麼你需要兩個'UNPIVOT'?示例數據中的「代碼」列在哪裏? –

+0

假設在DB中有代碼列。我不需要2個unpivot。我只是不知道如何在這種情況下添加字符列。 – Nick

+0

[你需要這個嗎?](http://www.sqlfiddle.com/#!6/eb53b/5) –

回答

0

你在找?

SELECT Chr, Value 
    FROM 
(
    SELECT t.* 
    FROM pc t 
    WHERE code = 3 
) s 
UNPIVOT 
(
    Value FOR Chr IN (Speed, Ram, Whatever, Other) 
) p 

輸出:

 
|  CHR | VALUE | 
-------------------- 
| Speed | S3 | 
|  Ram | R3 | 
| Whatever | W3 | 
| Other | O3 | 

這裏是SQLFiddle演示

+0

@Nick它解決了你的問題嗎? – peterm