I have a table (in MS Access) that stores in each record the start and end date for one event associated with an item. Multiple events may be associated with each item, and event time periods may overlap.
I will use the term ‘open event’ to mean an event that has a start date less than and an end date greater than a given date.
I would like a query that gives me the list of items that had at least one open event within a given time period, but which also have no open events at the end of the time period. Ideally, I would also like to list for each of these items the id of the last open event in the time period.
Here is a list of event records that represent some cases I need to have covered. The time period in question is 2012-03-20 to 2012-03-30:
eventId itemId startDate endDate
e1 i1 2012-03-21 2012-03-23 -- event open entirely inside of time period
e2 i2 2012-03-19 2012-03-21 -- event open at start date
e3 i3 2012-03-29 2012-03-31 -- event open at end date
e4 i4 2012-03-19 2012-03-26 -- multi-event item with event open at end date
e5 i4 2012-03-22 2012-03-25
e6 i4 2012-03-29 2012-03-31
e7 i4 2012-04-01 2012-04-30
e8 i5 2012-03-19 2012-03-25 -- multi-event item with no events open at end date
e9 i5 2012-03-22 2012-03-29
e10 i5 2012-03-25 2012-03-26
e11 i5 2012-04-01 2012-04-30
e12 i6 2012-03-13 2012-03-19 -- event not in time period at all
And here are the items (and their last-open events) that I’d like to see as a result of this query:
i1, e1
i2, e2
i5, e9 -- note that e9.endDate > e8.endDate and e10.endDate, and that e11 falls after the time period in question, so is not considered the last event for the item
You could
left jointo a subquery that lists all events that are open at the enddate. If you demand that a column from the subquery is null, you exclude all event/item combinations that match the subquery.