Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Mostrar lacunas entre datas no MySQL


nessa linha:
drop table if exists dates;
create table dates (d_from date, d_to date);
insert into dates values 
('2014-06-15'  , '2014-06-20'),
('2014-06-23'  , '2014-06-27' ),
('2014-06-29'  , '2014-06-30' );

select low.d_to, high.d_from, to_days(high.d_from) - to_days(low.d_to) - 1 as gap

from dates low, dates high
where high.d_from = (select min(d_from) from dates where d_from > low.d_to)
;

O que significa:unir a tabela a si mesma em datas de término/início adjacentes e calcular a diferença.
+------------+------------+------+
| d_to       | d_from     | gap  |
+------------+------------+------+
| 2014-06-20 | 2014-06-23 |    2 |
| 2014-06-27 | 2014-06-29 |    1 |
+------------+------------+------+