当缺少日期时选择1 - MYSQL

时间:2017-11-21 04:12:39

标签: mysql

我希望有条件或返回结果(1)当我的查询检测到我有一个丢失的日期并且我在用户的两个日期之间调用它。

正如您所看到的那样 2016年3月21日至2016年3月26日期间 。我想从我的查询中得到一个结果,我的查询中缺少日期。

你能告诉我如何做到这一点吗?

这是我的疑问:

select DISTINCT DOB from DATES where STR_TO_DATE(DOB, '%m/%d/%Y') BETWEEN '20160301' AND '20160331'

enter image description here

1 个答案:

答案 0 :(得分:1)

这样只会缺少日期。

select  case when count(DISTINCT DOB) = datediff('20160331','20160301') + 1 then 1 else 0 end 
from DATES 
where STR_TO_DATE(DOB, '%m/%d/%Y') BETWEEN '20160301' AND '20160331'

以下查询将为您提供总日期。

select asodate ,t1.dob 
from 
( SELECT @row := @row + interval 1 day as asofdate
FROM 
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t,
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t2, 
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t3, 
(select 0 union all select 1 union all select 3 union all select 4 union all select 5 union all select 6 union all select 6 union all select 7 union all select 8 union all select 9) t4, 
(SELECT @row:='2016-03-01' - interval 1 day) a
where @row < '2016-03-31') generateCalender
left join 
( select DISTINCT STR_TO_DATE(DOB, '%m/%d/%Y') as dob
from DATES 
where STR_TO_DATE(DOB, '%m/%d/%Y') BETWEEN '20160301' AND '20160331' ) t1
on asofdate = t1.dob

您可以通过添加条件来轻松找到所有缺少的日期。

where t1.dob is NULL