SQL Group BY, Top N Items for each Group

后端 未结 2 1682
一整个雨季
一整个雨季 2020-12-03 12:00

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         


        
相关标签:
2条回答
  • 2020-12-03 12:22
    ;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;
    
    0 讨论(0)
  • 2020-12-03 12:34

    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
    
    0 讨论(0)
提交回复
热议问题