I want to only return the most recent/max value from a set in SQL

240 Views Asked by At

I have a list of clients with a Payment ID that has changed over the years, but I'm only interested in returning the info from the most recent. This is my result after running:

     Select distinct 
    a.client 
    , a.payment_id 
    , max(a.update_year_month)  
    from Client_Data a

    group by 1,2
Client Payment ID Update Year_Month
A B 202005
A C 201907
A D 201706

I only want my query to pull in the most recent one regardless of the payment_id. However, I need to still bring in Payment ID for my larger query.

1

There are 1 best solutions below

6
Doug Currie On

Perhaps

select 
    a.client 
  , a.payment_id 
  , max(a.update_year_month)
from Client_Data a
group by 1 

or

select 
    a.client 
  , a.payment_id 
  , a.update_year_month
from Client_Data a
where a.update_year_month 
      = (select max(b.update_year_month)
          from Client_Data b where a.client = b.client)