postgresql转置行列苦难

时间:2013-09-18 00:29:03

标签: sql postgresql transpose

我已经完成了所有相似的主题,似乎无法解决我的问题。我有一张这样的桌子:

id[PK]        key[PK]     value
--------------------------------
22            ingfs       east1
22            storage     stgeast1
23            ingfs       east2
23            storage     stgeast2
24            ingfs       east3
24            storage     stgeast3

我想得到:

ingfs   storage
----------------
east1   stgeast1
east2   stgeast2
east3   stgeast3

我已尝试过数据透视表示例,但似乎无法获得任何工作。看起来这应该很简单,但我不能把头缠在它上面。提前感谢您的任何帮助。

RJL

2 个答案:

答案 0 :(得分:2)

select
    max(case when key = 'ingfs' then value end) as ingfs,
    max(case when key = 'storage' then value end) as storage
from Table1
group by id
order by 1, 2

<强> sql fiddle demo

答案 1 :(得分:0)

以下是否适合您?

WITH i AS (
    SELECT id, 
            value 
        FROM table_name 
        WHERE key = 'ingfs'),
s AS (
    SELECT id, 
            value 
        FROM table_name 
        WHERE key = 'storage')
SELECT i.value AS ingfs, 
        s.value AS storage
    FROM i
    JOIN s on ( i.id = s.id ) ;