-2

I have a database that contains Freight Data. I am trying to get the three ship countries with the highest average freight charges. I want to use only the last 12 months of order data, using as the end date the last Order Date in the Orders table. The first 10 entries of the Orders table are:

enter image description here

I am not able to figure out how to create the condition for the starting date. The query that I wrote is:

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

The error that I'm getting with this query is:

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.

UPDATE

I resolved this problem by using the following query:

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
Dale K
  • 25,246
  • 15
  • 42
  • 71
Deepansh Arora
  • 724
  • 1
  • 3
  • 15

2 Answers2

0

You can do this with window functions:

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
GMB
  • 216,147
  • 25
  • 84
  • 135
0

I resolved this problem by using the following query:

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
Deepansh Arora
  • 724
  • 1
  • 3
  • 15