在两个日期之间创建行

时间:2018-10-23 15:07:53

标签: sql oracle connect-by

我有下表。我需要为hire_dt到term_dt的每个月创建一行

id      hire_dt        term_dt
1      08/07/2017     02/20/2018

预期结果:

id    hire_dt          term_dt        Month   level_alias
1     08/07/2017       10/20/2017     201708    1
1     08/07/2017       10/20/2017     201709    2
1     08/07/2017       10/20/2017     201710    3

查询:

SELECT DISTINCT
ID,
HIRE_DT,
TERM_DT,
TO_CHAR(ADD_MONTHS(TRUNC(HIRE_DT, 'MM'), LEVEL -1), 'YYYYMM') AS MONTH,

LEVEL AS LEVEL_ALIAS

FROM  AHR
JOIN  HA ON ID = HA.id --AND RNK = 1
WHERE 1=1
CONNECT BY LEVEL <= 1 + MONTHS_BETWEEN(TRUNC(TERM_DT,'MM'),TRUNC(HIRE_DT,'MM'))
AND PRIOR ID = ID AND PRIOR HIRE_DT=HIRE_DT
AND PRIOR SYS_GUID() IS NOT NULL
AND AHR.ASSOC_AIN_ID = 1

结果:

id    hire_dt          term_dt        Month   level_alias
1     08/07/2017                      201708    1
1     08/07/2017       10/20/2017     201708    1
1     08/07/2017       10/20/2017     201709    2
1     08/07/2017       10/20/2017     201710    3

为什么我会收到null term_dt?

1 个答案:

答案 0 :(得分:0)

基于您提供的示例数据(有点误导; 2017年10月20日与2018年2月20日对比),请查看以下内容:

SQL> with test (id, hire_dt, term_dt) as
  2    (select 1, date '2017-08-07', date '2017-10-20' from dual)
  3  select id,
  4    hire_dt,
  5    term_dt,
  6    to_char(add_months(hire_dt, level - 1), 'yyyymm') month,
  7    level lvl
  8  from test
  9  connect by level <= months_between(term_dt, hire_dt) + 1;

        ID HIRE_DT    TERM_DT    MONTH         LVL
---------- ---------- ---------- ------ ----------
         1 08/07/2017 10/20/2017 201708          1
         1 08/07/2017 10/20/2017 201709          2
         1 08/07/2017 10/20/2017 201710          3

SQL>

可能需要修改,但是-正如我说的那样,使用您提供的信息就可以了(即我不知道您要连接什么表以及为什么连接)。