I’m working with a Postgres table named orders
that looks like this:
user_id product order_date
1 pants 7/1/2022
2 shirt 6/1/2022
1 socks 3/17/2023
3 pants 2/17/2023
4 shirt 3/13/2023
2 pants 8/15/2022
1 hat 4/15/2022
5 hat 3/14/2023
2 socks 12/3/2022
3 shirt 4/15/2023
4 socks 1/15/2023
Here is a dB Fiddle with the data:
https://www.db-fiddle.com/f/uNGjP7gpKwdPGrJ7XmT7k3/0
My goal is to output a table that shows the sequence of a customer’s orders. For example, customer 1 first purchased a hat, then purchased pants, and finally purchased socks.
Here is the desired output:
user_id first_order second_order third_order
1 hat pants socks
2 shirt pants socks
3 pants shirt <null>
4 socks shirt <null>
5 hat <null> <null>
I used RANK() OVER (PARTITION BY user_id ORDER BY order_date) AS rank
to arrange the sequence of the orders by user_id
. This works in "long" form. However, I’m not able to translate this into the form of the table above.
How would I do that?
Thanks for your help,
-Rachel
2
Answers
You can use a series of
left join
s on a subquery with the ranks. Your joining criteria can be tojoin
the relation on both the user name and an incremented rank number. This way, rank2
rows are joined onto rank1
rows for a given user, and so on:See fiddle.
You can do it using the conditional aggregation, using
group by
, case clause and the aggregation functionmax()
:Demo here