在SQL中使用GROUP BY选择2个最大值

时间:2019-04-30 18:09:46

标签: sql sql-server northwind

我需要编写一个查询,以显示每年和每个公司的2个最大贵订单。

我尝试过:

SELECT CompanyName, DATEPART(YEAR, OrderDate) AS OrderYear, MAX(Freight)
FROM Orders, Shippers
WHERE Shippers.ShipperID = Orders.ShipVia
GROUP BY CompanyName, DATEPART(YEAR, OrderDate)

但是我只得到第一个,我怎么也能得到第二个?

1 个答案:

答案 0 :(得分:1)

您可以使用行号执行此操作:

SELECT *
FROM (
  SELECT CompanyName, DATEPART(YEAR, OrderDate) AS OrderYear, Freight,
       ROW_NUMBER() OVER (PARTITION BY CompanyName, DATEPART(YEAR, OrderDate)  ORDER BY Freight DESC) AS RN
  FROM Orders
  JOIN Shippers ON Shippers.ShipperID = Orders.ShipVia
) X
WHERE X.RN < 3