Latest row per customer
Newest row per group with ROW_NUMBER, plus PostgreSQL's DISTINCT ON shortcut.
The task
You want each customer's most recent order, whole row, not just the date. MAX(order_date) in a GROUP BY loses the rest of the row.
The snippet
Runs unchanged on current versions of SQL Server, PostgreSQL, MySQL, SQLite and Oracle.
WITH ranked AS (
SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY customer_id
ORDER BY order_date DESC, id DESC) AS rn
FROM orders o
)
SELECT id, customer_id, order_date, amount, status
FROM ranked
WHERE rn = 1;
工作原理
ROW_NUMBER numbers each customer's orders newest-first and the filter keeps the first one. The id DESC tiebreaker makes the choice deterministic when two orders share the same order_date, which otherwise lets the engine pick arbitrarily. This scales fine with an index on (customer_id, order_date DESC, id DESC).
Variations
DISTINCT ON (PostgreSQL)
PostgreSQLSELECT DISTINCT ON (customer_id)
id, customer_id, order_date, amount, status
FROM orders
ORDER BY customer_id, order_date DESC, id DESC;
Questions that come up
Why not MAX(order_date) with GROUP BY?
Because the other columns would have to come from somewhere. Adding them to GROUP BY splits rows further, and joining back on MAX(order_date) returns every order tied at the latest date, not one row per customer.
Keep reading
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.