【问题标题】:Finding out Columns with missing dates from a table从表中找出缺少日期的列
【发布时间】:2017-03-04 19:30:58
【问题描述】:

我在 SQL Server 中有一个类似的表

身份证日期 1 2016 年 1 月 12 日 1 2016 年 2 月 12 日 ..................... ..................... ..................... 1 2016 年 12 月 31 日 2 2016 年 1 月 12 日 2 2016 年 2 月 12 日

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

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

【问题讨论】:

  • select * from table where Date = NULL;这是你想要的吗?
  • 没有。因为任何 ID 都没有空值。如果缺少任何日期,则整行也会丢失。如果 ID-3 的 '12/12/2016' 数据丢失。然后对于 12 月的数据,它将显示 30 个条目。所有正常数据的位置 - 它将显示 31 个条目。

标签: sql sql-server


【解决方案1】:

解释:

  1. 生成一个月的所有日期。感谢这个答案 Get All Dates of Given Month and Year in SQL Server
  2. 用不同的 id 交叉加入它并使用名称 all_possible_comb 。这将是所有 id 的全部 31 天。
  3. 现在将它与您的表正确连接并过滤空值以获取丢失的记录。

http://sqlfiddle.com/#!6/952d04/12

DECLARE @month AS INT = 12
DECLARE @Year AS INT = 2016

;WITH N(N)AS 
(SELECT 1 FROM(VALUES(1),(1),(1),(1),(1),(1))M(N)),
tally(N)AS(SELECT ROW_NUMBER()OVER(ORDER BY N.N)FROM N,N a),
all_dates as (SELECT datefromparts(@year,@month,N) date FROM tally
WHERE N <= day(EOMONTH(datefromparts(@year,@month,1)))),
all_possible_Comb as (select * from all_dates 
       cross join (select distinct id as id from table1) t)
select a.* from table1 t
right join all_possible_comb a
on t.id=a.id and t.date=a.date
where t.id is null

【讨论】:

    【解决方案2】:

    您可以编写的最短查询,假设您不需要不存在 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'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多