简体   繁体   中英

Select MAX Value for Each ROW - Oracle Sql

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).

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

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)

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