Search code examples
sqlgreatest-n-per-group

SQL Group By most recent date and sales value


I have the following sales table that displays the customer ID, their name, the order amount, and the order date.

ID Name Order Date
1 A 25 11/10/2006
1 A 10 5/25/2010
1 A 10 6/18/2018
2 B 20 3/31/2008
2 B 15 11/15/2010
3 C 35 1/1/2019
3 C 20 4/12/2007
3 C 10 3/20/2010
3 C 5 10/19/2012
4 D 15 12/12/2013
4 D 15 2/18/2010
5 E 25 12/11/2006
6 F 10 5/1/2016

I am trying to group the data so that for each customer it would only show me their most recent order and the amount, as per below:

ID Name Order Date
1 A 10 6/18/2018
2 B 15 11/15/2010
3 C 35 1/1/2019
4 D 15 12/12/2013
5 E 25 12/11/2006
6 F 10 5/1/2016

So far I've only been able to group by ID and Name, because adding the Order column would also group by that column as well.

SELECT 
  ID,
  Name,
  MAX(Date) 'Most recent date'
FROM Table
GROUP BY Customer, Customer

How can I also add the order amount for each Customer?


Solution

  • SELECT ID, Name, Order, Date FROM (
        SELECT *, ROW_NUMBER() OVER (PARTITION BY Name ORDER BY Date DESC) AS sn
        FROM your_table_name
    ) A WHERE sn = 1;