0

如何编写查询以查找以下数据空白。

--Scenario1 -- Query1 --在同一个表中查找间隙(例如 tableb )

ID      EFF_DT                                  TERM_DT 
800    6/15/2012 12:00:00.000 AM    10/14/2012 12:00:00.000 AM      -- GAP 
800    10/16/2012 12:00:00.000 AM    11/14/2012 12:00:00.000 AM
800    11/15/2012 12:00:00.000 AM    12/31/9999 12:00:00.000 AM

--Scenario2 -- Query2 --查找 2 个表之间的不匹配项 (tablea , tableb )

-- tablea  , sample data below 
ID      EFF_DT                                  TERM_DT 
400    6/15/2012 12:00:00.000 AM    10/14/2012 12:00:00.000 AM      
400    11/15/2012 12:00:00.000 AM    12/31/9999 12:00:00.000 AM

500    6/15/2012 12:00:00.000 AM    10/14/2012 12:00:00.000 AM      
500    10/15/2012 12:00:00.000 AM    11/14/2012 12:00:00.000 AM      
500    11/15/2012 12:00:00.000 AM    12/31/9999 12:00:00.000 AM

-- tableb, sample data below 
ID      EFF_DT                                  TERM_DT 
400    6/15/2012 12:00:00.000 AM    10/13/2012 12:00:00.000 AM      -- mismatch 
400    11/15/2012 12:00:00.000 AM    12/31/9999 12:00:00.000 AM

500    6/15/2012 12:00:00.000 AM    11/14/2012 12:00:00.000 AM      
500    11/15/2012 12:00:00.000 AM    12/31/9999 12:00:00.000 AM


-- Note 400 is a mismatch since ranges are different in both tables, 500 is okay (even though rows are split they still match )
-- Need to identify ID 400 

这些表有时有 1/1/1753 的低日期和 12/31/9999 的高日期。

尝试了以下查询,但它在第一种情况下会引发 oracle 错误。[ ORA-01841:(完整)年份必须介于 -4713 和 +9999 之间,并且不能为 0 ]

SELECT ID, TERM_DT AS gap_lower_bound, next_date AS gap_upper_bound
  FROM (SELECT t.*,
               LEAD (EFF_DT)
                  OVER (PARTITION BY ID ORDER BY EFF_DT)
                  next_date
          FROM TABLEB t)
 WHERE                                      -- trim(next_date) is not null and
      next_date > TERM_DT + 1

谢谢你。

4

1 回答 1

2

对于 Scenario1,让我们取样,

    ID    EFF_DT         TERM_DT 
____________________________________
    800 15-JUN-12   14-OCT-12 --GAP
    800 16-OCT-12   14-NOV-12
    800 15-NOV-12   31-DEC-12
    800 01-JAN-13   01-FEB-13  --GAP
    800 03-FEB-13   01-MAR-13

查询可能是

    SELECT term_dt
FROM
     (SELECT t.*,
          lead(eff_dt,1) OVER (ORDER BY eff_dt) AS next_date
     FROM lead_test t
     )
WHERE term_dt+1<>next_date;

结果:

 term_dt
__________
14-OCT-12
01-FEB-13

对于方案2:

select to_date('12/31/9999', 'mm/dd/yyyy')+1 from dual;抛出相同的错误。,

ORA-01841由于您使用的 where 子句中的条件,您会遇到错误TERM_DT + 1,因此最好更改/减少 . 中的值12/31/9999

于 2013-02-01T02:50:58.747 回答