从表中查找缺少日期的列

时间:2017-03-04 10:21:12

标签: sql sql-server

我在SQL Server中有一个像

的表
ID        Date
1          1/12/2016
1          2/12/2016
.....................
....................
.....................
1         31/12/2016
2          1/12/2016
2          2/12/2016

对于表格的每个ID,有31个日期条目。这意味着每个月的每一天都应该为每个ID输入条目。 现在对于某些错误,某些ID的某些日期缺少条目。 假设ID-3,'12 / 12/2016'日期缺失。缺少的日期完全是随机的。

现在如何找出哪个ID丢失了哪个日期。我的意思是我需要一个结果,可以显示2016年12月该表中缺少日期的ID。

2 个答案:

答案 0 :(得分:1)

说明:

  1. 生成一个月的所有日期。感谢这个答案 Get All Dates of Given Month and Year in SQL Server
  2. 将其与不同的ID交叉加入,并使用名称Data > Split text into columns... > Space。对于所有all_possible_comb,这将包含所有31天。
  3. 现在将它与您的表连接并过滤空值以获取丢失的记录。
  4. http://sqlfiddle.com/#!6/952d04/12

    id

答案 1 :(得分:0)

你可以写的最短的查询,假设很少的事情,你不需要没有id的日子(这将省略假期) (#table1是你的表)

select distinct a.date,b.id from #table1 a cross join (select distinct id
from #table1) b where convert(varchar,a.date,103)+convert(varchar,b.id) not 
in (select convert(varchar,date,103)+convert(varchar,id) from #table1)

如果您想要来自和迄今为止的数据,您只需指定条件之间的日期,例如

select distinct a.date,b.id from #table1 a cross join (select distinct id
from #table1) b where convert(varchar,a.date,103)+convert(varchar,b.id) not 
in (select convert(varchar,date,103)+convert(varchar,id) from #table1) and 
date between '2016-12-01' and '2016-12-31'
相关问题