11

我有一个 SQL 查询,它可以在给定的商店中获得前 5 名售出的商品。

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

销售表有 -> UPCCode、SaleDate、StoreId、TotalDollarSales

我正在寻找一个查询,它将在单个查询中返回每个商店销售的前 5 件商品。我可以编写多个查询并使用联合,但它似乎效率不高。

如何在单个查询中获得每家商店的前 5 件销售商品。

提前致谢。

4

2 回答 2

20
;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;
于 2013-03-05T15:58:28.270 回答
7

尝试这个:

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
于 2013-03-05T15:58:07.583 回答