I've got the following query, that looks up the TOP 5 Products matching the search. Each Product is associated with a Shop
SELECT TOP 5 * FROM Products p, Shops s WHERE p.ShopId = s.ShopId AND p.ProductName LIKE '%christmas%'
I need to extend this so that it returns me the TOP 5 Products in each Shop.
Could anyone let me know how the query could be modified to achieve this? - i.e. choose the TOP 5 products matching "%christmas%" in each shop (rather than the current which shows the TOP 5 products matching "%chrismas%" across all shops).
Try this
Here is a great solution I just found.
Select the TOP n Rows For Each Group Arnie Rowland, March 13, 2008
There are Multiple Rows for Each Category, and there is a desire to SELECT ONLY the TOP two (2) Rows per Category by Price. For example, from the following data:
The desired output is:
There are several methods to accomplish the desired output. This demonstration provides a Solution for SQL Server 2005 / SQL Server 2008 , and then a Solution for SQL Server 2000.
Create Sample Data for Both Solutions
SQL Server 2005 / SQL Server 2008 Solution
SQL Server 2005 / SQL Server 2008 Solution using a CTE (Added by: Jacob Sebastian)
SQL 2000 Solution
From: Select the TOP n Rows For Each Group
You're actually missing an ORDER BY to make the TOP meaningful, or any solution based on ROW_NUMBER which requires an ORDER BY.
Try this: