PostgreSQL动态地将行转置为列

时间:2019-03-27 10:56:43

标签: sql postgresql pivot crosstab

您好,我正在尝试使查询结果在每列1行中动态对齐,如果可以的话,请帮助我

例如,这是我的桌子

id , names , comm    , contrib
1    samp1   randtext     9
2    samp1   randtext     2
3    samp1   randtext     3 
5    samp2   randtext     4 
6    samp2   randtext     1   

那么我试图获得的结果就是

names  comm1    comm2    comm3    contrib1  contrib2  contrib3 
samp1  randtext,randtext,randtext    9      , 2       , 3
samp2  randtext,randtext,            4      , 1       ,  

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我们可以结合使用ROW_NUMBER和数据透视查询:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY names ORDER BY id) rn
    FROM your_table
)

SELECT
    names,
    MAX(CASE WHEN rn = 1 THEN comm END) comm1,
    MAX(CASE WHEN rn = 2 THEN comm END) comm2,
    MAX(CASE WHEN rn = 3 THEN comm END) comm3,
    MAX(CASE WHEN rn = 1 THEN contrib END) contrib1,
    MAX(CASE WHEN rn = 2 THEN contrib END) contrib2,
    MAX(CASE WHEN rn = 3 THEN contrib END) contrib3
FROM cte
GROUP BY
    names
ORDER BY
    names;