首页 > 解决方案 > 如何在sql中的表中按ID填充缺失的日期

问题描述

我有表 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)中使用。PS 我是 SQL 环境中编码的新手,我的背景是 ABAP

标签: sqldatabasedatejoinsql-insert

解决方案


您可以使用来自的日期来cross join区分来自,如下所示:empidab

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

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

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)

推荐阅读