SQL Query to Determine Top N Items for Each Store
To find the top N items sold for each store in a single query, we can leverage a combination of the GROUP BY and ROW_NUMBER() functions. Here's a comprehensive solution:
WITH s AS ( SELECT StoreID, UPCCode, tds, rn = ROW_NUMBER() OVER (PARTITION BY StoreID ORDER BY tds DESC) FROM ( SELECT StoreID, UPCCode, tds = SUM(TotalDollarSales) FROM Sales GROUP BY StoreID, UPCCode ) AS s2 ) SELECT StoreID, UPCCode, TotalDollarSales = tds FROM s WHERE rn <= 5 ORDER BY StoreID, TotalDollarSales DESC;
Understanding the Query
This approach efficiently retrieves the top-selling items for each store in a single SQL statement, avoiding the need for multiple queries or inefficient UNION operations.
The above is the detailed content of How to Find the Top N Items Sold at Each Store Using a Single SQL Query?. For more information, please follow other related articles on the PHP Chinese website!