1

I have one doubt. I need to find what is the latest occurrence for a specific list of Customers, let's say to simplify, I need it for 3 Customers out of 100. I need to check when it was the last time each of them got a bonus. The table would be:

EVENT_TBL 

Fields: Account ID, EVENT_DATE, BONUS ID, ....

Can you suggest a way to grab the latest (MAX) EVENT DATE (that means one row each)

I'm using SELECT...IN to specify the Account ID but not sure how to use MAX, Group BY etc etc (if ever needed).

1
  • example code and desired results? Commented Sep 25, 2017 at 13:43

2 Answers 2

4

Use the ROW_NUMBER() analytic function:

SELECT * FROM ( SELECT t.*, ROW_NUMBER() OVER ( PARTITION BY Account_id ORDER BY event_date DESC ) AS rn FROM EVENT_TBL t WHERE Account_ID IN ( 123, 456, 789 ) ) WHERE rn = 1 
Sign up to request clarification or add additional context in comments.

2 Comments

it returns: "rn Invalid Identifier)
@MorganForever did you include the AS rn part?
0

You can try

with AccountID_Max_EVENT_DATE as ( select AccountID, max(EVENT_DATE) MAX_D from EVENT_TBL group by AccountID ) SELECT E.* FROM EVENT_TBL E INNER JOIN AccountID_Max_EVENT_DATE M ON (E.AccountID = M.AccountID AND M.MAX_D = E.EVENT_DATE) 

1 Comment

This uses a self-join and may require two table scans. Also, if there are multiple entries with the same (maximum) date then this will return more than one row per account.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.