0

I have a table with account numbers and dates (amoung other columns). For each account number there are multiple entries with different dates. I want to return only the row with the most recent date and only account numbers that I have from another source.

This is what I've tried but I understand why this doesn't work. I just can't think of an alternative approach.

SELECT ACCOUNT_NUMBER, MAX(DATE) FROM PORTFOLIO WHERE ACCOUNT_NUMBER IN (444347, 899999, 887111, 220922) GROUP BY ACCOUNT_NUMBER 
1
  • 1
    What is wrong in the results that you are getting from your current query? Commented Feb 25, 2020 at 23:05

2 Answers 2

1

I want to return only the row with the most recent date and only account numbers that I have from another source.

I understand that you want the latest record per account number. If so, one solution is to use analytic functions:

select * from ( select p.*, rank() over(partition by account_number order by date desc) rn from portfolio p where account_number in (444347, 899999, 887111, 220922) ) t where rn = 1 

Another approach uses a correlated subquery for filtering:

select p.* from portfolio p where p.account_number in (444347, 899999, 887111, 220922) and p.date = ( select max(p1.date) from portfolio p1 where p1.account_number = p.account_number ) 
Sign up to request clarification or add additional context in comments.

3 Comments

Your suspicions are correct. Your methods are a little more advanced than I am comfortable with but I will study them. Thank you... Preacher had a more elegant solution.
@nicodemusmd: let me pinpoint that the other solution is exactly the same as the second query in my answer - and it was posted afterwards.
lol, I see. I saw his query before I realized you had two of them.
0
SELECT ACCOUNT_NUMBER, DATE FROM PORTFOLIO WHERE ACCOUNT_NUMBER IN (444347, 899999, 887111, 220922) and date = (select max(date) from portfolio b where portfolio.account_number = account_number) 

1 Comment

Thank you. That is what I was looking for.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.