I need to join table A and table B to create table C.
Table A and Table B store status flags for the IDs. The status flags (A_Flag and B_Flag) can change from time to ti
I'm going to solve this in SQL, assuming that you have a function called lag
(SQL Server 2012, Oracle, Postgres, DB2). You can get the same effect with a correlated subquery.
The idea is to get all the different time periods. Then join back to the original tables to get the flags.
I am having trouble uploading the code, but can get most of it. However, it starts with start ends, which you create by doing a union
(not union all
) of the four dates in one column: select a.start as thedate. This is then union'ed with a.end, b.start, and b.end.
with driver as (
select thedate as start, lag(thedate) over (order by thedate) as end
from startends
)
select startdate, enddate, a.flag, b.flag
from driver left outer join
a
on a.start >= driver.start and a.end <= driver.end left outer join
b
on b.start >= driver.start and b.end <= driver.end