按组分开并展平列信息

时间:2014-11-02 15:39:49

标签: sql postgresql pivot

问题设置

我有一张桌子

id    type    x    y
1     type1   1.0  2.0
2     type2   1.2  2.3
3     type1   1.2  2.4

我想将type1和type2的x,y分开如下:

id    x_type1   y_type1  x_type2    y_type2
1     1.0       2.0       
2                        1.2        2.3
3     1.2       2.4

我如何在postgresql中实现它?

1 个答案:

答案 0 :(得分:1)

我只会使用条件聚合:

select t.id,
       max(case when type = 'type1' then x end) as x_type1,
       max(case when type = 'type1' then y end) as y_type1,
       max(case when type = 'type2' then x end) as x_type2,
       max(case when type = 'type3' then y end) as y_type2
from table t
group by t.id;