请告诉我如何使用下面描述的方式拆分记录。
我有一个如下表
当前数据
EMPL | C2 | C3 | DateFrom | DateTo | C6 | C7
-----+----+----+------------+------------+----+----
1 | B | C | 11/27/2018 | 12/31/9999 | D | E
2 | B | C | 11/27/2018 | 05/31/2019 | D | E
3 | B | C | 11/27/2017 | 06/31/2019 | D | E
我需要根据当前年份将每一行分成两个或更多记录。
在EMPL 1的情况下,我需要将行分成两部分:一个必须输入当年的最后一天,另一个必须将DateFrom设置为明年的第一天,但DateTo应该为12/31 / 9999
对于EMPL 2,我需要将此记录分成两个记录,如示例所示
第3种情况应产生3条记录,每年一条。
结果
EMPL | C2 | C3 | DateFrom | DateTo | C6 | C7
-----+----+----+------------+------------+----+---
1 | B | C | 11/27/2018 | 12/31/2018 | D | E
1 | B | C | 01/01/2019 | 12/31/9999 | D | E
2 | B | C | 11/27/2018 | 12/31/2018 | D | E
2 | B | C | 01/01/2019 | 05/31/2019 | D | E
3 | B | C | 11/27/2017 | 12/31/2017 | D | E
3 | B | C | 01/01/2018 | 12/31/2018 | D | E
3 | B | C | 01/01/2019 | 06/31/2019 | D | E
答案 0 :(得分:1)
Oracle设置:
CREATE TABLE table_name ( EMPL, C2, C3, DateFrom, DateTo, C6, C7 ) AS
SELECT 1, 'B', 'C', DATE '2018-11-27', DATE '9999-12-31', 'D', 'E' FROM DUAL UNION ALL
SELECT 2, 'B', 'C', DATE '2018-11-27', DATE '2019-05-31', 'D', 'E' FROM DUAL UNION ALL
SELECT 3, 'B', 'C', DATE '2017-11-27', DATE '2019-06-30', 'D', 'E' FROM DUAL;
查询:
WITH years ( EMPL, C2, C3, DateFrom, DateTo, C6, C7, YearEnd ) AS (
SELECT t.*,
ADD_MONTHS( TRUNC( DateFrom, 'YYYY' ), 12 ) - 1
FROM table_name t
UNION ALL
SELECT EMPL,
C2,
C3,
YearEnd + 1,
DateTo,
C6,
C7,
CASE WHEN YearEnd + 1 < SYSDATE
THEN ADD_MONTHS( YearEnd, 12 )
ELSE DateTo
END
FROM years
WHERE YearEnd < DateTo
)
SELECT EMPL,
C2,
C3,
DateFrom,
LEAST( YearEnd, DateTo ) AS DateTo,
C6,
C7
FROM years
ORDER BY Empl, C2, C3, C6, C7, DateFrom;
输出:
EMPL C2 C3 DATEFROM DATETO C6 C7
---- -- -- ---------- ---------- -- --
1 B C 2018-11-27 2018-12-31 D E
1 B C 2019-01-01 9999-12-31 D E
2 B C 2018-11-27 2018-12-31 D E
2 B C 2019-01-01 2019-05-31 D E
3 B C 2017-11-27 2017-12-31 D E
3 B C 2018-01-01 2018-12-31 D E
3 B C 2019-01-01 2019-06-30 D E