Instruction
Awesome! We can also express the delta between two periods as a percentage. Look at the following query:
SELECT
DATEPART(Year, OrderDate) AS RevenueYear,
SUM(Amount) AS TotalRevenue,
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 decimal(10,2)),
2) AS DeltaPercentage
FROM Orders
GROUP BY DATEPART(Year, OrderDate)
ORDER BY DATEPART(Year, OrderDate);
Here is the result:
| RevenueYear | TotalRevenue | DeltaPercentage |
|---|---|---|
| 2016 | 218600.23 | NULL |
| 2017 | 655506.15 | 199.87 |
| 2018 | 273379.76 | -58.29 |
This time, the calculation in the last column is a bit more complicated:
- We divide the change between the current and previous period by the revenue value from the previous period.
- To avoid integer division, we cast the denominator to a decimal type with
CAST(SUM(Amount) AS decimal(10,2))). For larger numbers, you can of course increase the first argument ofdecimal(10,2). - We multiply the division result by
100to get the percentage value. - We round the percentage to two decimal places using the
ROUND(value, 2)function.
Exercise
The template query contains the code from the previous example. Modify it to show the revenue change as a percentage that's rounded to three decimal places.
Here's how you can count the revenue change as a percentage:
Remember to round the result to three decimal places.
Stuck? Here's a hint!
Use the following expression to calculate the last column:
ROUND(
100 *
(SUM(Amount) - LAG(SUM(Amount), 1)
OVER (ORDER BY DATEPART(Year, OrderDate),
DATEPART(Quarter, OrderDate)))
/ CAST(LAG(SUM(Amount), 1)
OVER (ORDER BY DATEPART(Year, OrderDate),
DATEPART(Quarter, OrderDate)) AS decimal(10,2)),
3) AS Delta




