I want to pull out top 3 selling products for different product category per tag. Data looks like this:
tag | product_name | product_category | order_count
tag1 | product1 | category1 | 100
tag1 | product2 | category2 | 80
tag1 | product3 | category2 | 60
tag1 | product4 | category3 | 50
......
I know how to pull out top 3 selling products per tag using ROW_NUMBER(), but it will return product1,product2,product3. I don't want product3 because it belongs to the same category as product2. I want product4 instead. How to do this in SQL server?
First ROW_NUMBER removes duplicate rows per tag and product_category, second ROW_NUMBER selects top 3 selling products per tag
Demo on
SQLFiddle
Next one uses a derived table
Demo on
SQLFiddle
I would suggest doing it with one select only
SQL Fiddle
You can use
RANK()
(orROW_NUMBER()
) as long as you usePARTITION BY
. This in combination withTOP()
should work well assuming you're using SQL Server 2005+:This will produce the following: