简体   繁体   中英

SQL MAX Query Multiple Columns

Trying to populate multiple columns based on one MAX value but the grouping returns multiple results. Is there a way I can tell SQL to only pull the values based on the MAX that I want?

Query:

Select a.ID, (MAX)a.PayDate, a.AgencyName
From a
Group By a.ID, a.AgencyName

What I need is the latest paydate per ID, then I want additional information in reference to that entry such as AgencyName (& more columns I want to add) but because of the grouping - SQL returns the latest paydate for each of the AgencyNames that the person has had - but I only want the AgencyName associated with the record that is Max Paydate for that ID. I know it's the grouping that does this but I am unsure how to proceed - any help greatly appreciated.

Thanks

Select a.ID,a.PayDate, a.AgencyName
From a
where exists (select 1 from a a1 where a1.id = a.id 
  having a.payDate = max(a1.paydate)
Group By a.ID,

I would just use a correlated subquery like this:

select a.*
from a
where a.paydate = (select max(a2.paydate) from a a2 where a2.id = a.id);

Note that this could return multiple rows if an id has duplicates on the most recent paydate . An alternative that guarantees one row is row_number() :

select a.*
from (select a.*,
             row_number() over (partition by id order by paydate desc) as seqnum
      from a
     ) a
where seqnum = 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM