I’m a bit stuck trying to figure out how to design an Oracle query, and although there are similar questions here none of them seem to quite address the issues I’m facing.
I have two tables and I want to join them:
PROJECT table
PROJECT_ID TITLE
101 First project
102 Second project
103 Third project
104 Fourth project
105 Fifth project
EVENT table
EVENT_ID PROJECT_FK EVENT_TYPE EVENT_DATE EVENT_DESC
201 101 301 2010-01-01 First event
202 101 301 2010-01-01 Second event
203 101 302 2010-01-02 Third event
204 102 301 2010-01-03 Fourth event
205 102 301 2010-01-04 Fifth event
206 104 301 2010-01-05 Sixth event
207 105 302 2010-01-06 Seventh event
I would like to get a list of each project’s data (from the PROJECT table) along with details of the most recent event, but only events of a single type (all other events should be ignored.) One row, and only one row, should be returned for each project (so if multiple matching events have the same date either one is fine, and if there are no events nulls/blanks should be returned in the event fields.)
This is what the output might look like:
SELECT <???> WHERE PROJECT_ID IN (101, 102, 103, 105) /* for event type 301 only */
PROJECT_ID TITLE EVENT_DATE EVENT_DESC
101 First project 2010-01-01 First event
102 Second project 2010-01-04 Fifth event
103 Third project NULL NULL
105 Fifth project NULL NULL
I’m finding this quite tricky as the only examples I can find either assume that the max(date) is unique (but here selecting by that will return the wrong row) or they assume there is a lot of duplication so GROUP BY will work.
Oracle 9i+, using ROW_NUMBER:
Oracle 9i+, Using WITH and ROW_NUMBER: