Sub topic 13
Calculating Period-over-Period Change
This chapter assumes you know basic SELECT, WHERE, and ORDER BY, aggregate functions, and inline views. You will use analytic functions to compare each row with an earlier or later row without removing detail from the result.
Compare neighboring rows with LAG and LEAD
LAG reads a value from an earlier row in the window order. LEAD reads a value from a later row. Both functions use OVER to define that order.
For monthly sales, the previous row is usually the previous available month:
SELECT sales_month,
amount,
LAG(amount) OVER (
ORDER BY sales_month
) AS previous_amount,
LEAD(amount) OVER (
ORDER BY sales_month
) AS next_amount
FROM monthly_sales
ORDER BY sales_month;The first row has no earlier row, so LAG returns NULL. The last row has no later row, so LEAD returns NULL.
The order inside OVER controls which rows are considered neighbors. It is separate from the final ORDER BY, which controls how Oracle displays the result.
Use offsets and default values
The second argument is the offset, or number of rows to move. The third argument supplies a value when that position does not exist.
SELECT sales_month,
amount,
LAG(amount, 2, 0) OVER (
ORDER BY sales_month
) AS amount_two_periods_ago,
LEAD(amount, 1, 0) OVER (
ORDER BY sales_month
) AS amount_next_period
FROM monthly_sales
ORDER BY sales_month;For the first two rows, amounttwoperiodsago is 0. For the final row, amountnext_period is 0. Choose a default carefully. NULL can distinguish “no neighboring row” from an actual amount of zero.
Calculate period-over-period change
Subtract the previous amount from the current amount to calculate the change. A percentage change divides that difference by the previous amount. NULLIF prevents division by zero.
SELECT sales_month,
amount,
LAG(amount) OVER (
ORDER BY sales_month
) AS previous_amount,
amount - LAG(amount) OVER (
ORDER BY sales_month
) AS change_from_previous,
100 * (
amount - LAG(amount) OVER (
ORDER BY sales_month
)
) / NULLIF(
LAG(amount) OVER (
ORDER BY sales_month
),
0
) AS percent_change
FROM monthly_sales
ORDER BY sales_month;The first percentage is NULL because there is no previous period. A zero previous amount also produces NULL rather than an invalid division.
For multiple entities, such as products or stores, add PARTITION BY so comparisons do not cross entity boundaries:
SELECT store_id,
sales_month,
amount,
amount - LAG(amount) OVER (
PARTITION BY store_id
ORDER BY sales_month
) AS change_from_previous
FROM monthly_sales
ORDER BY store_id, sales_month;Always use an ORDER BY that identifies a stable sequence. If two rows can have the same sales_month, add a unique tiebreaker.
Exercise
What does LAG(amount, 2, 0) return for the first row in a partition?
Show answer
It returns 0 because two earlier rows do not exist and 0 is the specified default.