如何在Oracle SQL中创建用于修复/填充间隙/重叠日期的SQL查询

bpzcxfmw  于 2023-04-29  发布在  Oracle
关注(0)|答案(1)|浏览(113)

我非常需要你的帮助。任何人都可以请帮助我如何建立一个查询(见下面的截图)。我已经为此头疼好几天了。

CREATE TABLE PROD_TABLE(Assignment_ID   number, Effective_START_Date date,  Effective_END_Date date);
INSERT INTO prod_table VALUES (30001,   TO_DATE('1/1/2001', 'MM/DD/YYYY'),  TO_DATE('2/1/2020', 'MM/DD/YYYY');
INSERT INTO prod_table VALUES (30001,   TO_DATE('2/2/2020', 'MM/DD/YYYY'),  TO_DATE('2/2/2021', 'MM/DD/YYYY');
INSERT INTO prod_table VALUES (30001,   TO_DATE('2/3/2021', 'MM/DD/YYYY'),  TO_DATE('3/19/', 'MM/DD/YYYY');
INSERT INTO prod_table VALUES (30001,   TO_DATE('3/20/2023', 'MM/DD/YYYY'), TO_DATE('12/31/4712', 'MM/DD/YYYY');
INSERT INTO prod_table VALUES (44444,   TO_DATE('3/20/2023', 'MM/DD/YYYY'), TO_DATE('12/31/4712', 'MM/DD/YYYY');

CREATE TABLE STAGING_TABLE(Assignment_ID    number, Effective_START_Date date,  Effective_END_Date date);
INSERT INTO prod_table VALUES (30001,   TO_DATE('1/1/2001', 'MM/DD/YYYY'),  TO_DATE('2/1/2020', 'MM/DD/YYYY');
INSERT INTO prod_table VALUES (30001,   TO_DATE('2/2/2020', 'MM/DD/YYYY'),  TO_DATE('5/4/2020', 'MM/DD/YYYY');
INSERT INTO prod_table VALUES (30001,   TO_DATE('5/5/2020', 'MM/DD/YYYY'),  TO_DATE('2/2/2021', 'MM/DD/YYYY');
INSERT INTO prod_table VALUES (30001,   TO_DATE('2/3/2021', 'MM/DD/YYYY'),  TO_DATE('3/19/2021', 'MM/DD/YYYY');
INSERT INTO prod_table VALUES (30001,   TO_DATE('3/20/2023', 'MM/DD/YYYY'),     TO_DATE('12/31/4712', 'MM/DD/YYYY');
INSERT INTO prod_table VALUES (44444,   TO_DATE('3/20/2023', 'MM/DD/YYYY'),     TO_DATE('4/19/2023', 'MM/DD/YYYY');
INSERT INTO prod_table VALUES (44444,   TO_DATE('4/20/2023', 'MM/DD/YYYY'),     TO_DATE('12/31/4712', 'MM/DD/YYYY');

我有2个表,我需要合并他们都基于assignment_id。但我的问题是,如果有差距/重叠的日期。

l5tcr1uw

l5tcr1uw1#

找到两个表之间重叠的日期范围,这将使结果的数量增加一点,然后使用GREATESTLEAST收缩开始/结束日期:

SELECT prod_table.Assignment_ID,
       GREATEST(staging_table.effective_start_date,prod_table.effective_start_date) effective_end_date,
       LEAST(staging_table.effective_end_date,prod_table.effective_end_date) effective_end_date
  FROM PROD_TABLE,
       STAGING_TABLE
 WHERE prod_table.Assignment_ID = staging_table.Assignment_ID
   AND prod_table.effective_start_date < staging_table.effective_end_date
   AND prod_table.effective_end_date > staging_table.effective_start_date

输出:

相关问题