// SQL snippet

Lag compare within a group

LAG and FIRST_VALUE with a shared PARTITION BY: row-over-row deltas without self-joins.

Main statement
All engines

The task

You want, per order, how much bigger or smaller it is than the customer's previous order.

The snippet

Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.

All engines
SELECT customer_id, order_date, amount,
       LAG(amount) OVER (PARTITION BY customer_id
                         ORDER BY order_date, id) AS prev_amount,
       amount - LAG(amount) OVER (PARTITION BY customer_id
                                  ORDER BY order_date, id) AS change_vs_prev
FROM orders
ORDER BY customer_id, order_date;

仕組み

LAG reads the previous row's amount inside the same customer partition; the first row per customer gets NULL because nothing precedes it. PARTITION BY resets the ordering per customer, so a customer's rows never compare against another customer's. LEAD is the mirror image, reading the next row, and both take an offset argument to look further back or ahead.

Variations

Also compare to the customer's first order

SELECT customer_id, order_date, amount,
       amount - LAG(amount) OVER (PARTITION BY customer_id
                                  ORDER BY order_date, id) AS change_vs_prev,
       amount - FIRST_VALUE(amount) OVER (PARTITION BY customer_id
                                          ORDER BY order_date, id) AS change_vs_first
FROM orders
ORDER BY customer_id, order_date;

Questions that come up

Can LAG return a default instead of NULL?

Yes: LAG(amount, 1, 0) looks back one row and returns 0 when there is none. Use it when downstream arithmetic would rather have a zero than a NULL, but keep in mind the first row then reports a fake change.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.