我有一个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

Sales表具有-> UPCCode,SaleDate,StoreId,TotalDollarSales

我正在寻找一个查询,该查询将在一次查询中返回我为每个商店售出的排名前5位的商品。我可以编写多个查询并使用并集,但效率似乎不高。

如何在单个查询中获取每个商店的销售量最高的5件商品。

提前致谢。

最佳答案

;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;

10-07 12:38