Pivot Unpivot附加栏目

时间:2013-08-24 21:31:24

标签: sql pivot

如果我有一些表格例如:

   [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 个答案:

答案 0 :(得分: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 演示