小编典典

每年的SELECT TOP记录

sql

我想回顾一下我的sql技能,现在我想在northwinddb上运行一个简单的查询以向我显示每年的顶级客户,但是无论我使用什么,只要使用TOP函数,就只会显示1条记录分区,这是我的T-
SQL代码

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

阅读 245

收藏
2021-04-07

共1个答案

小编典典

您可以在SQL Server 2008中更紧凑地执行此操作,如下所示:

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
  );
2021-04-07