How can I compare each row with the previous row using LAG?
Quick answer
Use LAG(reading) with a window ordered by the reading date, and partition the window by device so each device has its own sequence. Subtract the lagged reading from the current reading to calculate change. The first row in each device’s sequence has no preceding value, so LAG() returns NULL there. [S1]
The question, the details, the next step.
A practical checklist
Replace the example table and column names with names from your database.
Choose the column that defines the intended order within each device’s series.
Use
PARTITION BYfor the group that must not be compared with other groups.Decide how to order rows when a device has more than one row with the same month.
Confirm that current minus previous is the direction of change you want.
A few more useful answers
Why is the first change NULL?
LAG() returns NULL when there is no preceding row in that device’s partition. Subtracting NULL also yields NULL in this example. [S1]
Does LAG compare with the previous calendar month?
It compares with the preceding row in the window’s ordered sequence, not necessarily a calendar month that is exactly one month earlier. [S1]
How do I show the previous value without calculating a difference?
Keep the LAG(reading) OVER (...) AS previous_reading expression and remove the subtraction expression from the SELECT list.
Sources
References used for this guide.
- [S1] SQLite Window Functions: lag() sqlite.org · Checked
