WITH dates_from AS (
SELECT id, date_from FROM Table1
UNION
SELECT id, date_to + interval '1 second' FROM Table1
UNION
SELECT id, date_from FROM Table2
UNION
SELECT id, date_to + interval '1 second' FROM Table2
),
dates_to AS (
SELECT id, date_to FROM Table1
UNION
SELECT id, date_from - interval '1 second' FROM Table1
UNION
SELECT id, date_to FROM Table2
UNION
SELECT id, date_from - interval '1 second' FROM Table2
),
ranges AS (
SELECT df.id, date_from, MIN(date_to) AS date_to
FROM dates_from df
JOIN dates_to dt ON dt.id = df.id AND dt.date_to > df.date_from
GROUP BY df.id, date_from
)
SELECT r.id,
t1.param1, t1.param2, t2.param3,
r.date_from, r.date_to
FROM ranges r
LEFT JOIN Table1 t1 ON t1.id = r.id AND t1.date_from <= r.date_to and t1.date_to >= r.date_from
LEFT JOIN Table2 t2 ON t2.id = r.id AND t2.date_from <= r.date_to and t2.date_to >= r.date_from
ORDER BY r.id, r.date_from
WITH dates_from AS (
SELECT id, date_from FROM Table1
UNION
SELECT id, date_to + interval '1 second' FROM Table1
UNION
SELECT id, date_from FROM Table2
UNION
SELECT id, date_to + interval '1 second' FROM Table2
),
dates_to AS (
SELECT id, date_to FROM Table1
UNION
SELECT id, date_from - interval '1 second' FROM Table1
UNION
SELECT id, date_to FROM Table2
UNION
SELECT id, date_from - interval '1 second' FROM Table2
),
ranges AS (
SELECT df.id, date_from, MIN(date_to) AS date_to
FROM dates_from df
JOIN dates_to dt ON dt.id = df.id AND dt.date_to > df.date_from
GROUP BY df.id, date_from
)
SELECT r.id,
t1.param1, t1.param2, t2.param3,
r.date_from, r.date_to
FROM ranges r
LEFT JOIN Table1 t1 ON t1.id = r.id AND t1.date_from <= r.date_to and t1.date_to >= r.date_from
LEFT JOIN Table2 t2 ON t2.id = r.id AND t2.date_from <= r.date_to and t2.date_to >= r.date_from
ORDER BY r.id, r.date_from
Но всё равно что то не выходит(