显示MySQL中日期之间的差距

时间:2014-06-07 18:20:36

标签: mysql sql

如何在mysql中显示剩余/补充日期?

例如,在我的表中有2列,一个快照为
from_date>14-06-2014 and to_date<01-07-2014

会给出这个输出:

From date   || To_date
15-06-2014  || 20-06-2014
23-06-2014  || 27-06-2014 
29-06-2014  || 30-06-2014 

我希望能够显示我们有差距且没有记录的日期,如下所示:

2 //21-06-2014 - 23-06-2014
1 //28-06-2014 

这可能吗? 谢谢

1 个答案:

答案 0 :(得分:3)

沿着这些方向:

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)
;

这意味着:在相邻的结束/开始日期将表连接到自身并计算差异。

+------------+------------+------+
| d_to       | d_from     | gap  |
+------------+------------+------+
| 2014-06-20 | 2014-06-23 |    2 |
| 2014-06-27 | 2014-06-29 |    1 |
+------------+------------+------+