I'm trying to write a join bewteen two tables where a date value in the left table falls into a time slot on the right table. So, for example if I have:
TABLE A TABLE B
ID TIMESTMP ID TIMESMTP VALUE
1 8/31/2012 2:00 PM 1 8/30/2012 4:00 AM A
2 8/29/2012 3:00 PM 1 8/31/2012 1:00 PM B
3 7/04/2012 5:00 AM 1 8/31/2012 3:00 PM C
2 8/20/2012 1:00 PM A
The result should be:
TABLE C
ID TIMESTMP VALUE
1 8/31/2012 2:00 PM B
2 8/29/2012 3:00 PM A
3 7/04/2012 5:00 AM null
I want to find the corresponding record in table B with the max timestamp which is still < the timestamp in table A. If there is not a matching id (outer join) or there are no timestamps in B < the timestamp in A, it should return null.
Thanks!
UPDATE
Here is the solution I went with using lead() as suggested by Gordon Linoff:
SELECT b.value, a.*
FROM table_a a
LEFT OUTER JOIN (
SELECT id, timestmp,
lead(timestmp) over(PARTITION BY id ORDER BY timestmp) AS next_timestmp,
value FROM table_b
) b
ON a.id = b.id
AND (a.timestmp >= b.timestmp AND (a.timestmp < b.timestmp OR b.timestmp IS NULL))