Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Group BY, Top N Items for each Group

Tags:

sql

sql-server

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.

like image 869
arunlalam Avatar asked Mar 05 '13 15:03

arunlalam


People also ask

How do you SELECT top and rows for each group in SQL?

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.

Can we use top with GROUP BY clause?

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.


2 Answers

;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;
like image 103
Aaron Bertrand Avatar answered Sep 30 '22 23:09

Aaron Bertrand


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
like image 36
Dumitrescu Bogdan Avatar answered Oct 01 '22 00:10

Dumitrescu Bogdan