Very well done! In the previous explanation, we calculated the quarterly revenue in each year. Now, let's say we want a report containing:
- quarterly revenue values.
- annual revenue values.
- the grand total revenue value.
Here's an example of the result we'd like to achieve:
Sound complicated? Here's a query to handle it:
SELECT
DATEPART(Year, OrderDate) AS RevenueYear,
DATEPART(Quarter, OrderDate) AS RevenueQuarter,
SUM(Amount) AS TotalRevenue
FROM Orders
GROUP BY ROLLUP(
DATEPART(Year, OrderDate),
DATEPART(Quarter, OrderDate)
)
ORDER BY
DATEPART(Year, OrderDate),
DATEPART(Quarter, OrderDate);
We introduced a small change in the GROUP BY
clause. Instead of:
GROUP BY
DATEPART(Year, OrderDate),
DATEPART(Quarter, OrderDate)
we used:
GROUP BY ROLLUP(
DATEPART(Year, OrderDate),
DATEPART(Quarter, OrderDate)
)
Let's run the query and see what happens.