简体   繁体   中英

How to transform table with postgresql

I want to select this fields from db:

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

but all i have is like:

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

How I can transform my table to be like what I need? Thanks

One method is conditional aggregation:

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;

Another uses 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM