日期间隔 SQL

Date Interval SQL

我有一个包含货运数据的数据库。我试图获得平均运费最高的三个船舶国家。我只想使用最近 12 个月的订单数据,使用订单 table 中的最后一个订单日期作为结束日期。订单 table 的前 10 个条目是:

我不知道如何为开始日期创建条件。我写的查询是:

SELECT ShipCountry, ROUND(AVG(Freight),2) AS AverageFreight
FROM [dbo].[Orders]
WHERE YEAR(OrderDate) < YEAR(MAX(OrderDate)) 
GROUP BY ShipCountry
ORDER BY AverageFreight DESC

我在这个查询中遇到的错误是:

An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.

更新

我使用以下查询解决了这个问题:

SELECT TOP 3 ShipCountry, ROUND(AVG(Freight), 2) AS AverageFreight
FROM [dbo].[Orders]
WHERE OrderDate >= (SELECT DATEADD(mm,-12,(SELECT MAX(OrderDate) FROM [dbo].[Orders]))) 
GROUP BY ShipCountry
ORDER BY AverageFreight DESC

您可以使用 window 函数执行此操作:

SELECT ShipCountry, ROUND(AVG(Freight),2) AS AverageFreight
FROM (SELECT o.*, MAX(OrderDate) OVER() as MaxOrderDate FROM [dbo].[Orders] o) o
WHERE OrderDate >= DATEADD(year, -1, MaxOrderDate) 
GROUP BY ShipCountry
ORDER BY AverageFreight DESC

我使用以下查询解决了这个问题:

SELECT TOP 3 ShipCountry, ROUND(AVG(Freight), 2) AS AverageFreight
FROM [dbo].[Orders]
WHERE OrderDate >= (SELECT DATEADD(mm,-12,(SELECT MAX(OrderDate) FROM [dbo].[Orders]))) 
GROUP BY ShipCountry
ORDER BY AverageFreight DESC