查找日期范围之间的丢失记录

时间:2020-01-22 16:48:58

标签: sql sql-server join

在一个巨大的存储过程(在SQL Server中)的最后,我创建了两个CTE。一种带有某些日期范围(每6个月间隔一次),另一种带有某些记录。 假设我表B中的日期范围是2020年1月1日至2010年1月1日(间隔为6个月)

Start        End
----------------------
2020-01-01 | 2020-07-01
...     ...
other years here
...     ...
2010-01-01 | 2010-07-01

在表A上出现这种情况:

Name     Date
-----------------
John    2020-01-01
John    2019-01-01
John    2018-07-01
...     ...
Rob     2020-01-01
Rob     2019-07-01
Rob     2018-07-01
...     ...

我正在尝试生成一个这样的记录集:

Name   MissingDate
-----------------
John    2019-07-01
...     ...
John    2010-01-01

Rob     2019-01-01
...     ...
Rob     2010-01-01

我得了流感,现在我几乎不知道自己是谁,我希望情况很清楚,如果有人可以帮助我,我将非常感激。

1 个答案:

答案 0 :(得分:0)

如果您想要缺少日期(似乎是按月显示),则生成所有可用日期并取出您拥有的日期。

with cte as (
      select start, end
      from dateranges
      union all
      select dateadd(month, 1, start), end
      from cte
      where start < end
    )
select n.name, cte.start
from cte cross join
     (select distinct name from tablea) n left join
     tablea a
     on a.date = cte.start and a.name = n.name
where a.date is null;