Instruction
That's all we wanted to teach you in this part. It's time to wrap things up! First, let's review what we've learned:
- To show the total revenue for each year, use
DATEPART():SELECT DATEPART(Year, OrderDate) AS RevenueYear, SUM(Amount) AS TotalRevenue FROM Orders GROUP BY DATEPART(Year, OrderDate) ORDER BY DATEPART(Year, OrderDate);
- To show the total revenue for each quarter/month in each year, use
DATEPART()twice:SELECT DATEPART(Year, OrderDate) AS RevenueYear, DATEPART(Quarter, OrderDate) AS RevenueQuarter, ... GROUP BY DATEPART(Year, OrderDate), DATEPART(Quarter, OrderDate);
- To show the total revenue on all aggregation levels, add
ROLLUP():... GROUP BY ROLLUP( DATEPART(Year, OrderDate), DATEPART(Quarter, OrderDate) ) ...
- To show the revenue from the previous year, use
LAG():LAG(SUM(Amount), 1) OVER (ORDER BY DATEPART(Year, OrderDate))
- To calculate the difference between the current period and the previous period, use:
SUM(Amount) - LAG(SUM(Amount), 1) OVER (ORDER BY DATEPART(Year, OrderDate)) AS Delta
- To calculate the difference between the current period and the previous period as a percentage, use:
ROUND(100 * ( SUM(Amount) - LAG(SUM(Amount), 1) OVER (ORDER BY DATEPART(Year, OrderDate)) / CAST(LAG(SUM(Amount), 1) OVER (ORDER BY DATEPART(Year, OrderDate)) AS float)), 2) AS DeltaPercentage
- To create a revenue in quarters report, use:
SELECT DATEPART(Year, OrderDate) AS Year, SUM(CASE WHEN DATEPART(Quarter, OrderDate) = 1 THEN Amount ELSE 0 END) AS Q1, ... FROM Orders GROUP BY DATEPART(Year, OrderDate) ORDER BY DATEPART(Year, OrderDate);
How about a quick quiz?
Exercise
Click to continue.



