2013-03-05 26 views
8

Belirli bir mağazada en çok satılan 5 ürün alır bir SQL Sorgu var.SQL Group BY, her grup için en iyi N öğe

SELECT TOP 5 S.UPCCode, SUM(TotalDollarSales) FROM Sales S 
WHERE S.StoreId = 1 
GROUP BY S.UPCCode 
ORDER BY SUM(S.TotalDollarSales) desc 

Satış tablo var - Ben tek sorguda bana mağazaların her biri için satılan ilk 5 öğe dönecektir bir sorgu için arıyorum> UPCCode, SatışTarihi StoreID, TotalDollarSales

. Birden çok sorgu yazabilirim ve bir sendika kullanabilirim ancak etkili görünmüyor.

Her bir mağaza için en çok satılan 5 ürünü tek bir sorguda nasıl alabilirim.

Şimdiden teşekkürler.

+0

olası yinelenen http://stackoverflow.com/questions/757763/top-n-problem-with-group -by-maddesi) –

cevap

16
;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; 
([GROUP BY deyimiyle TOP N sorun] arasında
7

bu deneyin:

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