Мне удалось достичь желаемого результата с помощью запроса ниже. Также доступно для демонстрации здесь: SQL Fiddle . Оставьте последнее предложение order by
при создании представления, оно было включено сюда только для того, чтобы представить результаты разумно.
Настройка схемы PostgreSQL 9.6 :
CREATE TABLE Table1
("start_date" timestamp, "end_date" timestamp, "val" varchar(20))
;
INSERT INTO Table1
("start_date", "end_date", "val")
VALUES
('2000-01-01 00:00:00', '2000-01-31', 'APPLE'),
('2000-02-01 00:00:00', NULL, 'ORANGE')
;
CREATE TABLE Table2
("start_date" timestamp, "end_date" timestamp, "val" varchar(20))
;
INSERT INTO Table2
("start_date", "end_date", "val")
VALUES
('2000-01-01', '2000-01-15', 'TOMATO'),
('2000-01-16', NULL, 'LETTUCE')
;
CREATE TABLE Table3
("start_date" timestamp, "end_date" timestamp, "val" varchar(3))
;
INSERT INTO Table3
("start_date", "end_date", "val")
VALUES
('1999-01-12 00:00:00', NULL, 'CAR')
;
Запрос 1 :
with ends as (
select end_date from Table1 where end_date is not null union
select end_date from Table2 where end_date is not null union
select end_date from Table3 where end_date is not null
)
select
d.start_date
, least(e.end_date, lead(d.start_date,1) over(order by d.start_date) - INTERVAL '1 DAY') as end_date
, table1.val as t1_val
, table2.val as t2_val
, table3.val as t3_val
from (
select start_date from Table1 union
select start_date from Table2 union
select start_date from Table3
) d
left join lateral (
select ends.end_date from ends where ends.end_date > d.start_date
order by end_date
limit 1
) e on true
left join table1 on d.start_date between table1.start_date and coalesce(table1.end_date,current_date)
left join table2 on d.start_date between table2.start_date and coalesce(table2.end_date,current_date)
left join table3 on d.start_date between table3.start_date and coalesce(table3.end_date,current_date)
order by
start_date, end_date
Результаты :
| start_date | end_date | t1_val | t2_val | t3_val |
|----------------------|----------------------|--------|---------|--------|
| 1999-01-12T00:00:00Z | 1999-12-31T00:00:00Z | (null) | (null) | CAR |
| 2000-01-01T00:00:00Z | 2000-01-15T00:00:00Z | APPLE | TOMATO | CAR |
| 2000-01-16T00:00:00Z | 2000-01-31T00:00:00Z | APPLE | LETTUCE | CAR |
| 2000-02-01T00:00:00Z | (null) | ORANGE | LETTUCE | CAR |