Overview
Show how revenue changed from one day to the next with LAG(), and handle the first day, which has no previous value.
- LAG(x) OVER (ORDER BY ...)
- The first row gets NULL
- COALESCE() for a default
Short Course
LAG(x) OVER (ORDER BY day) reads the previous row's value, so each day can
be compared with the one before. Trap: the first row has no previous one, so
LAG returns NULL, and any maths with NULL is NULL. COALESCE gives a
default.
SELECT day, visitors,
visitors - LAG(visitors) OVER (ORDER BY day) AS change
FROM traffic; -- the first day's change is NULL
Task
Return each day, its revenue and the change from the previous day, with 0
for the first day, ordered by day. In the database below, revenue went up by
30 on March 2.
Database
Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.
| dayTEXT | revenueINTEGER |
|---|---|
| 2024-03-01 | 100 |
| 2024-03-02 | 130 |
| 2024-03-03 | 90 |
Test Suites
Pending
Next
Output