2014-10-27 101 views
0

我有一个包含数字和日期的表(每个日期和日期不一定是固定间隔)。我想知道一个数字不在表格中的日期数。循环或递归sql查询

我有什么(只是举个例子,日期和 “chiffres” 比较复杂):

date      | chiffre 
2014-09-30    |  2 
2014-09-29    |  1 
2014-09-28    |  2 
2014-09-27    |  2 
2014-09-26    |  1 
2014-09-25    |  2 
2014-09-24    |  2 

等等

我需要为数字 “1” 是什么:

actual_number_of_real_dates_between_two_given_dates 
    1 
    3 

我的实际查询感谢戈登·利诺夫

select count(n.id) as difference 
from nums n inner join 
    (select min(date) as d1, max(date) as d2 
     from (select date from nums where chiffre=1 order by date desc limit 2) d 
    ) dd 
where n.date between dd.d1 and dd.d2 

如何用3测试第2行? 3与4等...不仅是最后2?没有“限制2” 我应该使用循环吗?或者我可以没有?

回答

0

如果你正在努力寻找在表1 S之间的差距,你应该用下一个“1”开始:

select n.*, 
     (select date 
     from nums n2 
     where n2.chiffre = 1 and n2.date > n.date 
     order by date 
     limit 1 
     ) next_date 
from nums n 
where chiffre = 1; 

然后用这个作为一个子查询得到你想要的东西:

select n.*, 
     datediff(coalesce(next_date, now()), date) as days_between 
from (select n.*, 
      (select date 
       from nums n2 
       where n2.chiffre = 1 and n2.date > n.date 
       order by date 
       limit 1 
      ) next_date 
     from nums n 
     where chiffre = 1 
    ) n; 
+0

请问什么是sysdate?谢谢 – sam12 2014-10-27 15:58:44

+0

我试着用datediff(next_date,date_tirage)替换为days_between,但我有一个错误子查询返回多于一行 – sam12 2014-10-27 16:12:29

+0

@ sam12。 。 。两者都应该有一个“极限1”。 – 2014-10-27 18:51:10