Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: Find Missing Dates Between a Date Range

I need some help with a mysql query. I've got db table that has data from Jan 1, 2011 thru April 30, 2011. There should be a record for each date. I need to find out whether any date is missing from the table.

So for example, let's say that Feb 2, 2011 has no data. How do I find that date?

I've got the dates stored in a column called reportdatetime. The dates are stored in the format: 2011-05-10 0:00:00, which is May 5, 2011 12:00:00 am.

Any suggestions?

like image 292
Laxmidi Avatar asked Jul 01 '11 17:07

Laxmidi


1 Answers

This is a second answer, I'll post it separately.

SELECT DATE(r1.reportdate) + INTERVAL 1 DAY AS missing_date
FROM Reports r1
LEFT OUTER JOIN Reports r2 ON DATE(r1.reportdate) = DATE(r2.reportdate) - INTERVAL 1 DAY
WHERE r1.reportdate BETWEEN '2011-01-01' AND '2011-04-30' AND r2.reportdate IS NULL;

This is a self-join that reports a date such that no row exists with the date following.

This will find the first day in a gap, but if there are runs of multiple days missing it won't report all the dates in the gap.

like image 105
Bill Karwin Avatar answered Sep 27 '22 22:09

Bill Karwin