Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Limit response for each sku

I have a table called purchases and want to get purchases for each sku but only last 2 purchases for each sku.
How can I do that?

dbfiddle

my purchase table sql:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

CREATE TABLE purchase
(
id SERIAL PRIMARY KEY,
sku TEXT NOT NULL,
date DATE NOT NULL
)

my desired response:

enter image description here

>Solution :

You can utilise row_number(). From your limited sample data it looks like you want the lowest-Id values per SKU, amend the order-by criteria if that’s not correct:

SELECT id, sku, date 
FROM (
  select *, row_number() over(partition by sku order by date desc) rn
  from purchase
)p
where rn <= 2
order by sku, date;

DB<>Fiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading