SQL 如何将正确的日期分配给连续日期列中的多个空值

SQL How to assign correct dates to multiple nulls in sequential date columns

我有一个员工的连续日期范围,中间有空值。 处理空值的逻辑如下所述:

如果 todate 为 null 且下一条记录 fromdate 有值,则 todate 为(下一条记录 fromdate-1)
如果 todate 为 null 并且没有下一条记录 fromdate 则默认 todate 为 01/08/2020

Current Data

Required Data

这应该可以帮助您入门,但由于您没有说明您使用的是哪些 dbms,因此扣除一天的语法可能会有很多变化。

CREATE TABLE mytable(
   FROMDATE DATE  NOT NULL
  ,TODATE   DATE 
);
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('15/02/2016','30/04/2016');
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('1/05/2016',NULL);
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('2/06/2016','16/10/2016');
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('17/10/2016','31/12/2016');
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('1/01/2017','14/02/2017');
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('15/02/2017','31/12/2017');
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('1/01/2018','14/02/2018');
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('15/02/2018','20/02/2018');
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('21/02/2018','31/03/2018');
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('1/04/2018','31/12/2018');
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('1/01/2019','31/03/2019');
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('1/04/2019','31/12/2019');
INSERT INTO mytable(FROMDATE,TODATE) VALUES ('1/01/2020',NULL);

select
    fromdate
  , todate                                                        as todate_raw
  , coalesce(todate,lag(fromdate,1) over(order by fromdate DESC)) as todate_new
from mytable
order by fromdate
fromdate   | todate_raw | todate_new
:--------- | :--------- | :---------
2016-02-15 | 2016-04-30 | 2016-04-30
2016-05-01 | null       | 2016-06-02
2016-06-02 | 2016-10-16 | 2016-10-16
2016-10-17 | 2016-12-31 | 2016-12-31
2017-01-01 | 2017-02-14 | 2017-02-14
2017-02-15 | 2017-12-31 | 2017-12-31
2018-01-01 | 2018-02-14 | 2018-02-14
2018-02-15 | 2018-02-20 | 2018-02-20
2018-02-21 | 2018-03-31 | 2018-03-31
2018-04-01 | 2018-12-31 | 2018-12-31
2019-01-01 | 2019-03-31 | 2019-03-31
2019-04-01 | 2019-12-31 | 2019-12-31
2020-01-01 | null       | null      

db<>fiddle here