SQL Fiddle
的Oracle 11g R2架構設置:
CREATE TABLE A AS
SELECT TO_DATE('1-Jan-15', 'DD-MON-YY') AS start_date, TO_DATE('10-Jan-15', 'DD-MON-YY') AS end_date, 2 AS column_A FROM DUAL
UNION ALL SELECT TO_DATE('11-Jan-15', 'DD-MON-YY') AS start_date, TO_DATE('21-Jan-15', 'DD-MON-YY') AS end_date, 3 AS column_A FROM DUAL
UNION ALL SELECT TO_DATE('22-Jan-15', 'DD-MON-YY') AS start_date, TO_DATE('31-Jan-15', 'DD-MON-YY') AS end_date, 4 AS column_A FROM DUAL
UNION ALL SELECT TO_DATE('1-Feb-15', 'DD-MON-YY') AS start_date, TO_DATE('10-Feb-15', 'DD-MON-YY') AS end_date, 5 AS column_A FROM DUAL
UNION ALL SELECT TO_DATE('11-Feb-15', 'DD-MON-YY') AS start_date, TO_DATE('12-Feb-15', 'DD-MON-YY') AS end_date, 6 AS column_A FROM DUAL;
CREATE TABLE B AS
SELECT TO_DATE('1-Jan-15', 'DD-MON-YY') AS start_date, TO_DATE('20-Jan-15', 'DD-MON-YY') AS end_date, 4 AS column_B FROM DUAL
UNION ALL SELECT TO_DATE('21-Jan-15', 'DD-MON-YY') AS start_date, TO_DATE('31-Jan-15', 'DD-MON-YY') AS end_date, 5 AS column_B FROM DUAL
UNION ALL SELECT TO_DATE('1-Feb-15', 'DD-MON-YY') AS start_date, TO_DATE('5-Feb-15', 'DD-MON-YY') AS end_date, 6 AS column_B FROM DUAL
UNION ALL SELECT TO_DATE('6-Feb-15', 'DD-MON-YY') AS start_date, TO_DATE('12-Feb-15', 'DD-MON-YY') AS end_date, 7 AS column_B FROM DUAL;
查詢1:
WITH all_dates AS (
SELECT start_date AS "date", 0 AS isEnd FROM A
UNION
SELECT end_date, 1 FROM A
UNION
SELECT start_date, 0 FROM B
UNION
SELECT end_date, 1 FROM B
ORDER BY 1, 2
),
all_paired_dates AS (
SELECT "date" AS start_date,
LEAD("date") OVER (ORDER BY "date") AS end_date
FROM all_dates
)
SELECT d.start_date,
d.end_date,
a.column_A,
b.column_B
FROM all_paired_dates d
INNER JOIN A
ON ( d.start_date BETWEEN a.start_date AND a.end_date
AND d.end_date BETWEEN a.start_date AND a.end_date)
INNER JOIN B
ON ( d.start_date BETWEEN b.start_date AND b.end_date
AND d.end_date BETWEEN b.start_date AND b.end_date)
Results:
| START_DATE | END_DATE | COLUMN_A | COLUMN_B |
|----------------------------|----------------------------|----------|----------|
| January, 01 2015 00:00:00 | January, 10 2015 00:00:00 | 2 | 4 |
| January, 11 2015 00:00:00 | January, 20 2015 00:00:00 | 3 | 4 |
| January, 21 2015 00:00:00 | January, 21 2015 00:00:00 | 3 | 5 |
| January, 22 2015 00:00:00 | January, 31 2015 00:00:00 | 4 | 5 |
| February, 01 2015 00:00:00 | February, 05 2015 00:00:00 | 5 | 6 |
| February, 06 2015 00:00:00 | February, 10 2015 00:00:00 | 5 | 7 |
| February, 11 2015 00:00:00 | February, 12 2015 00:00:00 | 6 | 7 |
什麼是你想要的輸出背後的cryteria?你有什麼嘗試? – Eggplant
作爲一個方面說明:*我並不總是使用Oracle11g,但是當我這樣做時,我通過** psql ***連接... – Eggplant