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

How to take n rows of data from a table referring data from a column in the same table? (SQL)

I have a table with many data and a sample is as follows

product_table data data2 data3 data4 data5 data6 data7
product id 001 002 003 004 005 006 007
product name a b c d e f g
status available not available damaged available available not available damaged
order id 1 2 3 4 5 6 7 9

I need to extract 2 order ids from each of the statuses from one query.

The out put I want is as follows

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

status order id
available 1
available 4
not available 2
not available 6
damaged 3
damaged 7

I tried using "Limit" but it only brings out the first few data which is in the table.

Query I used

Select order id , status
from table product_table
limit 2
;

output I got was

status order id
available 1
not available 2

>Solution :

You can partition the database by status and use row_number to extract two records.

    select status, order_id from (
     select status, order_id, row_number() over (partition by status) as rn from product_table) 
where rn <=2;
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