如何使用PostgreSQL转换表

时间:2019-01-03 02:16:19

标签: sql postgresql pivot

我想从数据库中选择此字段:

order_id | item1_category | item2_category | item3_category
1        | book           | food           | drink

但是我所拥有的就像:

order_id | item_category
1        | book
1        | food
1        | drink

如何将表格转换为所需的表格?谢谢

1 个答案:

答案 0 :(得分:2)

一种方法是条件聚合:

select order_id,
       max(item_category) filter (where seqnum = 1) as item_category_1,
       max(item_category) filter (where seqnum = 2) as item_category_2,
       max(item_category) filter (where seqnum = 3) as item_category_3
from (select t.*,
             row_number() over (partition by order_id order by item_category) as seqnum
      from t
     ) t
group by order_id;

另一个人使用array_agg()

select order_id,
       (array_agg(item_category order by item_category))[1] as item_category_1,
       (array_agg(item_category order by item_category))[2] as item_category_2,
       (array_agg(item_category order by item_category))[3] as item_category_3
from t
group by order_id;