1

我有一个具有以下结构的表:

id    key data
1     A   10
1     B   20
1     C   30

我需要编写一个查询,以便将这些键作为列,将值作为行。

例如:

  id A  B  C
  1 10 20 30

我尝试过使用 union 和 case 但我得到 3 行而不是 1 行

有什么建议吗?

4

1 回答 1

1

最直接的方法是:

SELECT DISTINCT "id", 
   (SELECT "data" FROM Table1 WHERE "key" = 'A') AS "A",
   (SELECT "data" FROM Table1 WHERE "key" = 'B') AS "B",
   (SELECT "data" FROM Table1 WHERE "key" = 'C') AS "C"
FROM Table1

或者您可以使用 PIVOT:

SELECT * FROM 
  (SELECT "id", "key", "data" FROM Table1)
PIVOT (
  MAX("data") 
    FOR ("key") IN ('A', 'B', 'C'));

sqlfiddle demo

于 2013-10-21T13:01:30.897 回答