sql >> Database teknologi >  >> RDS >> Sqlserver

SQL Group BY, Top N elementer for hver gruppe

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


  1. PostgreSQL 9.1:Sådan sammenkædes rækker i array uden dubletter, JOIN en anden tabel

  2. Få en liste over alle funktioner og procedurer i en Oracle-database

  3. SQL - Forskel mellem COALESCE og ISNULL?

  4. Returner en DML Triggers Type på en tabel i SQL Server