I’ve been using SQL for a few years, and this type of problem comes up here and there, and I haven’t found an answer. But perhaps I’ve been looking in the wrong places – I’m not really sure what to call it.
For the sake of brevity, let’s say I have a table with 3 columns: Customer, Order_Amount, Order_Date. Each customer may have multiple orders, with one row for each order with the amount and date.
My Question: Is there a simple way in SQL to get the DATE of the maximum order per customer?
I can get the amount of the maximum order for each customer (and which customer made it) by doing something like:
SELECT Customer, MAX(Order_Amount) FROM orders GROUP BY Customer;
But I also want to get the date of the max order, which I haven’t figured out a way to easily get. I would have thought that this would be a common type of question for a database, and would therefore be easy to do in SQL, but I haven’t found an easy way to do it yet. Once I add Order_Date to the list of columns to select, I need to add it to the Group By clause, which I don’t think will give me what I want.
Apart from self-join you can do:
There’s a good article reviewing various approaches.
And in Oracle, db2, Sybase, SQL Server 2005+ you would use
RANK() OVER.Note: If
Customerhas more than one order with maximumOrder_Amount(i.e. ties), usingRANK()function would get you all such orders; to get only first one, replaceRANK()withROW_NUMBER().