Selecting data for the max date record in an aggregate query

I am trying to write a query with following fields:


The data has multiple records for each ID.  The Insurance is always SP.  I want to create a query that will return the
Max(Date) and the Amount associated with the Max(Date).


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

SELECT ID, Insurance, Amount,PayDate from tbl T where paydate=(select max(paydate) from tbl where ID=T.ID)

NB you may get more than one line for a given ID if there was more than one payment on the same max(Paydate).

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
GPSPOWAuthor Commented:

Worked Great!
Jim HornMicrosoft SQL Server Developer, Architect, and AuthorCommented:
Or, using a subquery..
SELECT ID, Insurance, yt_max.max_date, yt.PayDate
FROM YourTable yt
   SELECT ID, Insurance, Max(Date) as max_date
   FROM YourTable
   GROUP BY id, Insurance) yt_max ON yt.ID = yt_max.ID AND = yt_max.max_date

Open in new window

I have an article called SQL Server GROUP BY Solutions, scroll down to '5. Aggregate AND values from a single row that make up the aggregate: Subquery'
Only because it wasn't mentioned...

You can use row_number() for this
SELECT ID, Insurance, Amount,PayDate
      SELECT ID, Insurance, Amount,PayDate, row_number() over(partition by ID order by PayDate DESC) as rn
      FROM YourTable
      ) as derived
WHERE rn = 1

Open in new window

Here you can only get one row per ID even if there happens to be more than 1 payment on a paydate
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.