patternMinor
MAX for each subset
Viewed 0 times
subsetmaxforeach
Problem
I have a table that looks like this:
So, I need to get the latest (MAX(event_date)), non-null person_id per item_id. We have come up with a fairly simple PL/SQL approach to this, but were trying to get the job done with straight SQL. Anyone have an idea?
Just as a side-note, the event_id will not always be sequential like this. We have two redundant DB servers.
Thanks ahead of time.
+---------------------------------------------+
| EVENT_ID | ITEM_ID | PERSON_ID | EVENT_DATE |
+---------------------------------------------+
| 123 | 1 | 2 | 21-AUG-03 |
| 124 | 1 | 3 | 22-AUG-03 |
| 125 | 1 | 45 | 23-AUG-03 |
| 126 | 1 | (null) | 24-AUG-03 |
| 127 | 2 | 2 | 25-AUG-03 |
| 128 | 2 | 6 | 26-AUG-03 |
| 129 | 2 | 1 | 27-AUG-03 |
+---------------------------------------------+So, I need to get the latest (MAX(event_date)), non-null person_id per item_id. We have come up with a fairly simple PL/SQL approach to this, but were trying to get the job done with straight SQL. Anyone have an idea?
Just as a side-note, the event_id will not always be sequential like this. We have two redundant DB servers.
Thanks ahead of time.
Solution
The following requires only one full table scan.
SELECT Item_ID, Person_ID, Event_Date FROM
(
SELECT Event_ID, Person_ID, Item_ID, Event_Date
, MAX(EVENT_DATE) OVER (PARTITION BY Item_ID) HighEventDate
FROM Event_Table WHERE Person_ID IS NOT NULL
)
WHERE Event_Date = HighEventDate;Code Snippets
SELECT Item_ID, Person_ID, Event_Date FROM
(
SELECT Event_ID, Person_ID, Item_ID, Event_Date
, MAX(EVENT_DATE) OVER (PARTITION BY Item_ID) HighEventDate
FROM Event_Table WHERE Person_ID IS NOT NULL
)
WHERE Event_Date = HighEventDate;Context
StackExchange Database Administrators Q#2361, answer score: 7
Revisions (0)
No revisions yet.