Per customer ordered by date then orderid: return customerid, orderdate, amount, and amount minus their previous…
SQLLevel: IntermediateWindow functions
Per customer ordered by date then order_id: return customer_id, order_date, amount, and amount minus their previous orders amount (diff_vs_prev, NULL for the first).
Table definitions (from the source exercise):
CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
Hints
- Distinguish a missing value from zero, an empty string and false.
- Test comparison, aggregation and filtering on a tiny missing-value example.
Answer
Approach: LAG(amount) partitioned by customer.
SELECT customer_id, order_date, amount,
amount - LAG(amount) OVER (PARTITION BY customer_id
ORDER BY order_date, order_id) AS diff_vs_prev
FROM orders;
The source uses SQLite with a MySQL compatibility layer. Date and string functions are dialect dependent; the query is preserved as published.
Source and licence: SQL Practice Lab — Ebrahim Sharifi · MIT