Latest Order per Customer
Medium · Grouping
SELECT DISTINCT ON (key) ... keeps only the first row for each key. Which row is "first" is decided by ORDER BY, which must start with the same key.
For every customer who has orders, return name, order_id, ordered_on and total of their most recent order (any status). If two orders share the latest date, take the one with the higher id. Customer names are unique. Sort by name.