0

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

1
  • With PostgreSQL you probably want to crosstab. Commented Jan 3, 2019 at 2:20

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

I try the array_agg and it works, thanks a lot for introducing me with that function :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.