【问题标题】:How to fill missing dates by ID in a table in sql如何在sql中的表中按ID填充缺失的日期
【发布时间】:2020-08-15 09:34:55
【问题描述】:

我有表 A,它有日期和 EMPID,例如下面

date          EMPID     
8/06/19        1
8/07/19        1         
8/08/19        1         
8/09/19        1        
8/07/19        2          
8/09/19        2        
8/12/19        2     

我也有一个日期范围的表 B

date
...        
8/05/19
8/06/19
8/07/19
8/08/19
8/09/19
8/10/19
8/11/19
8/12/19
8/13/19
...

我的表 A 缺少日期和 EMPID。​​

如何将两个表合并为下表。

Date           EMPID
8/05/19        1
8/06/19        1
8/07/19        1
8/08/19        1
8/09/19        1
8/10/19        1
8/11/19        1
8/12/19        1
8/13/19        1
8/05/19        2
8/06/19        2
8/07/19        2
8/08/19        2
8/09/19        2
8/10/19        2
8/11/19        2
8/12/19        2
8/13/19        2

提前致谢。 这正在 SSRS 的数据集(SQL)中使用。 附言我是 SQL 环境中编码的新手,我的背景是 ABAP

【问题讨论】:

    标签: sql database date join sql-insert


    【解决方案1】:

    您可以将cross join 与来自a 的不同empid 与来自b 的日期不同,如下所示:

    select b.date, a.empid
    from (select distinct empid from a) a
    cross join b 
    

    或者,如果您正在寻找a 中的insert“缺失”日期,那么您可以使用带有not exists 条件的insert ... select 语法:

    insert into a (date, empid)
    select b.date, a.empid
    from (select distinct empid from a) a
    cross join b 
    where not exists (select 1 from a a1 where a1.empid = a.empid and a1.date = b.date)
    

    【讨论】:

      猜你喜欢
      • 2013-10-05
      • 2015-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多