PRAGYA SHARMA
PRAGYA SHARMA

Reputation: 23

How to fetch first 4 rows for each column value in SQL

I am running the following query:

select item, product, design, price 
from product 
fetch first 4 rows only

It is fetching all first 4 rows from the complete database, but suppose I have 10 items and every item has 10 products and I want to fetch any 4 products from each item. How do I do that?

Upvotes: 0

Views: 348

Answers (1)

Data_Enginner_Suraj
Data_Enginner_Suraj

Reputation: 76

Your question is absolutely very logical and I don't know how you received 2 negative votes but I appreciate you for asking this logical question.

I understood your question very well and the attached below script will provide you with the expected result: (will provide you the 4 products from each item)

select test.item, test.product, test.design, test.price from(
select item, product, design, price, row_number() over(partition by item order by product asc) as rn
from product) as test
where test.rn<=4;

please use this script to get the expected result and let me know for any additional information.

Thanks!

Upvotes: 1

Related Questions