I have a SQL Query which gets gets top 5 sold items at a given store.
SELECT TOP 5 S.UPCCode, SUM(TotalDollarSales) FROM Sales S
WHERE S.StoreId = 1
GROUP BY S.UPCCode
ORDER BY SUM(S.TotalDollarSales) desc
The Sales table has -> UPCCode, SaleDate, StoreId, TotalDollarSales
I am looking for a query which will return me Top 5 items sold for each of the stores in a single query. I can write multiple queries and use a union but it doesn't seem efficient.
How can I get the top 5 sold items for each store in a single query.
Thanks in advance.
Selecting a top n records for each category from any table, can be done easily using row_number function which generates a sequential integer to each row within a partition of a result set.
Typically, these are accomplished using the TOP or LIMIT clause. Problem is, Top N result sets are limited to the highest values in the table, without any grouping. The GROUP BY clause can help with that, but it is limited to the single top result for each group.
;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;
try this:
select ss.StoreId,is.*
from (select distinct StoreId from Sales) ss
cross apply (SELECT TOP 5 S.UPCCode, SUM(TotalDollarSales) as SumTotalDollarSales FROM Sales S
WHERE S.StoreId = ss.StoreId
GROUP BY S.UPCCode
ORDER BY SUM(S.TotalDollarSales) desc) is
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With