Sample Header Ad - 728x90

How to force Redshift/Postgres to aggregate nth_value?

1 vote
1 answer
332 views
I'm trying to retrieve the 2nd, 3rd, 4th order/transaction from an orders table using a query that looks like this: select customer_email, nth_value(created_at, 1) over (partition by customer_email), nth_value(created_at, 2) over (partition by customer_email), nth_value(created_at, 3) over (partition by customer_email), nth_value(created_at, 4) over (partition by customer_email) from fact_orders where group by customer_email, created_at limit 100 My goal is to get the 1st, 2nd, 3rd, and 4th order for each customer. I'm forced to do a group by on customer_email and created_at, which results in a row for each order and date by a customer. The nth_value yields the correct results, but I would prefer a result set that looks as so: customer_email, first_order, second_order, third_order, fourth_order With only 1 record per customer. How can I achieve this?
Asked by john (153 rep)
Jul 10, 2018, 04:43 AM
Last activity: Apr 21, 2025, 11:03 AM