Skip to content
Advertisement

Select first 10 rows for every 5 of a unique column

In a Postgres DB, given the following simplified dataset of orders:

How can I write a query to select the the first 5 unique store id’s, and the first 10 orders per store ordered by oldest to newest, resulting in a maximum of 50 rows returned? For example:


My goal is to process orders from oldest to newest, but process the oldest 10 orders per store as I can batch them with the Shopify API which would be more efficient.

For example, in my code I will combine it to something like:

So I can run 5 API calls in parallel for each store.

I’ve tried multiple queries, including the following:

But I cannot limit the rows to 10 per store ID

Advertisement

Answer

demo:db<>fiddle

1 a) Return only one record per store using DISTINCT ON b) Identify the top 5 stores ordering by the date. 2. These stores can be used in a lateral join to filter the orders per store, again using the updated_at order.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement