Introduction
LEAD and LAG
7. Deltas
FIRST_VALUE, LAST_VALUE, NTH_VALUE
Revision

Instruction

Good job! LEAD can be extremely useful when we want to calculate deltas, i.e. differences between two values. A typical example may look like this:

SELECT
  day,
  clicks,
  LEAD(clicks) OVER(ORDER BY day),
  clicks - LEAD(clicks) OVER(ORDER BY day) 
FROM statistics
WHERE website_id = 2;

The above query calculates day-to-day deltas: the last column shows the difference in clicks between the current day and the next day. From a business point of view, this could easily tell us a lot about the website: if the deltas for many rows are positive, and possibly increasing, then the website is expanding. If, in turn, the deltas are mostly negative, we can start to worry about the performance of the website.

Exercise

For website_id = 1, show each statistics row: day, revenue, revenue on the next day and the difference between these two values.

Stuck? Here's a hint!

Use LEAD(revenue) and the right ORDER BY clause twice.

Console

Code editor

Result

TableConsole