All right, let's get started! We're going to tackle nested CTEs.
If you take a look into SQL Server's documentation, you will find out that you cannot put one CTE inside the parentheses of another CTE. Luckily, we can still use a simple technique to create nested CTEs. Take a look at the query:
WITH TotalSalesman AS (
SELECT
S.Id AS SId,
C.Id AS CId,
SUM(Distance) AS SumKilometers
FROM Salesman S
INNER JOIN DailySales DS
ON S.Id = DS.SalesmanId
INNER JOIN City C
ON S.CityId = C.Id
GROUP BY S.Id,
C.Id
),
MaxSalesman AS (
SELECT
CId,
MAX(SumKilometers) AS MaxKilometers
FROM TotalSalesman
GROUP BY CId
)
SELECT
AVG(MaxKilometers) AS AvgMaxKilometers
FROM MaxSalesman;
The trick is that the second query, MaxSalesman
, uses the first CTE, TotalSalesman
, in the FROM
clause (FROM TotalSalesman
). That means that once we define the first CTE, we can freely use it in subsequent CTEs.
Now, what does that query do? In the first CTE, we find the total number of kilometers driven in each city by each salesperson (on all days). In the second CTE, we take these sums and choose the person with the maximal distance in each city. Finally, in the outer query, we find the average maximal distance across all cities.
As you know, it's impossible to use one aggregate function inside another. Nested CTEs are a simple way to get rid of that restriction.