SELECT TOP record for each year

社会主义新天地 提交于 2019-12-01 09:13:50

问题


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 only 1 record gets display no matter on what I partition by, This is my T-SQL code

SELECT DISTINCT TOP 1 C.CompanyName
, YEAR(O.OrderDate) AS Year
, SUM(Quantity) OVER(PARTITION BY C.CompanyName, YEAR(O.OrderDate)) AS Total
FROM Customers C JOIN Orders O
    ON C.CustomerID = O.CustomerID JOIN [Order Details] OD
    ON O.OrderID = OD.OrderID

回答1:


You can do this bit more compactly in SQL Server 2008 as follows:

select top (1) with ties
  C.CompanyName,
  Year(O.OrderDate) as Yr,
  sum(OD.Quantity) as Total
from Orders as O
join Customers as C on C.CustomerID = O.CustomerID
join "Order Details" as OD on OD.OrderID = O.OrderID
group by C.CompanyName, Year(O.OrderDate)
order by 
  row_number() over (
    partition by Year(O.OrderDate)
    order by sum(OD.Quantity) desc
  );



回答2:


Thank you for the help. I found a way that allows me to change the number of top customers i want to see for each year. By using Sub queries and Row_Number

SELECT CompanyName
,yr
,Total
FROM(SELECT CompanyName
, yr
, Total
, ROW_NUMBER() OVER(PARTITION BY yr ORDER BY yr, Total DESC) AS RowNumber
FROM(SELECT DISTINCT CompanyName
    , YEAR(O.OrderDate) AS yr
    ,  SUM(OD.Quantity) OVER(PARTITION BY CompanyName
                            , YEAR(O.OrderDate)) As Total
    FROM Customers C JOIN Orders O
        ON C.CustomerID = O.CustomerID JOIN [Order Details] OD
        ON O.OrderID = OD.OrderID) Tr)Tr2
Where RowNumber <= 1



回答3:


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


来源:https://stackoverflow.com/questions/9618559/select-top-record-for-each-year

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!