循环或递归的sql查询

时间:2014-10-27 15:40:13

标签: mysql sql loops subquery

我有一个包含数字和日期的表格(每个日期和日期不一定是固定间隔的1个数字)。我希望得到一个数字不在表中的日期计数。

我所拥有的(只是一个例子,日期和“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

我的实际问题归功于Gordon Linoff

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” 我应该使用循环吗?或者我可以不用吗?

1 个答案:

答案 0 :(得分:0)

如果你想找到表格中1之间的差距,你应该从下一个“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;