Skip to content
Advertisement

Find most recent row per user and day in sql query

I want to find the most recent purchase per customer for each date (a customer might make multiple purchases on a given date and I want the most recent for that date). My dataframe looks something like the following:

The output of the query should give me something like the following (I return one row per customer/date combination and order by customer/date. I don’t care about the Type – whether it is Credit or Debit):

Here is my code so far:

The example I gave is a simplification of the data I am working with and some of the filtering conditions, but should capture the main problem I am facing. Not really sure if that is on the right track, but it seems unhappy with the ‘Group by’ when I run the query. I am new to sql and would love help!

Advertisement

Answer

This query:

gets the most recent date for each customer.
Join it to the main table to get the rows that contain the most recent date for each customer:

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement