Return customerid, orderdate, orderid, and a running count of that customers orders so far (orderno), ordered within…
SQLLevel: IntermediateWindow functions
Return customer_id, order_date, order_id, and a running count of that customers orders so far (order_no), ordered within each customer by date then order_id.
Table definitions (from the source exercise):
CREATE TABLE customers(customer_id INTEGER PRIMARY KEY, name TEXT, city TEXT, signup_date TEXT, credit_score INTEGER);
CREATE TABLE orders(order_id INTEGER PRIMARY KEY, customer_id INTEGER, order_date TEXT, amount REAL, rep_id INTEGER, discount REAL);
Hints
- Define one output row and the source-table keys.
- Check duplicates, NULLs and the order of filtering and aggregation.
Answer
Approach: ROW_NUMBER, or COUNT(*) OVER a growing frame - ROW_NUMBER is simplest.
SELECT customer_id, order_date, order_id,
ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY order_date, order_id) AS order_no
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