SELECT TOP record for each year

前端 未结 3 1384
天涯浪人
天涯浪人 2021-01-14 10:18

I am trying to recap on my sql skill, now I am trying to run a simple query on northwinddb to show me the top customer for each year, but as soon as I use the TOP function o

3条回答
  •  无人及你
    2021-01-14 10:59

    Three steps: first sum quantities grouped by company and year, then order the results by quantity, then filter first row by group only.

    ; WITH sums as (
       SELECT C.Companyname, YEAR(O.OrderDate) AS Year, sum (Quantity) Total
         FROM Customers C JOIN Orders O
        ON C.CustomerID = O.CustomerID JOIN [Order Details] OD
        ON O.OrderID = OD.OrderID
        group by C.Companyname, YEAR(O.OrderDate)
    )
    with ordering as (
       select Companyname, Year, Total,
              row_number() over (partition by CompanyName, Year order by Total desc) rownum
          from sums
    )
    select *
    from ordering
    where rownum = 1
    

提交回复
热议问题