Latest Order per Customer
sqlSQLinterview-prepintermediate
Use ROW_NUMBER() to keep only the newest row in each group.
SELECT customer_id, id AS order_id, total, order_date
FROM (
SELECT o.*,
ROW_NUMBER() OVER (PARTITION BY o.customer_id ORDER BY o.order_date DESC) AS rn
FROM orders o
) AS ranked
WHERE rn = 1;