I have the following Oracle query:
SELECT id,
DECODE(state, 'Open', state_in, NULL) AS open_in,
DECODE(state, 'Not Open', state_in, NULL) AS open_out,
FROM (
SELECT id,
CASE WHEN state = 'Open'
THEN 'Open'
ELSE 'Not Open'
END AS state,
TRUNC(state_time) AS state_in
FROM ...
)
This gives me data like the following:
id open_in open_out
1 2009-03-02 00:00:00
1 2009-03-05 00:00:00
1 2009-03-11 00:00:00
1 2009-03-26 00:00:00
1 2009-03-24 00:00:00
1 2009-04-13 00:00:00
What I would like is data like this:
id open_in open_out
1 2009-03-02 00:00:00 2009-03-05 00:00:00
1 2009-03-11 00:00:00 2009-03-24 00:00:00
That is, keep all the unique pairs of id/open_in and pair with them the earliest open_out that follows open_in. There can be any number of unique open_in values for a given id, and any number of unique open_out values. It is possible that a unique id/open_in will not have a matching open_out value, in which case open_out should be null for that row.
I feel like some analytic function, maybe LAG or LEAD, would be useful here. Perhaps I need MIN used with a PARTITION.