2014-10-27 122 views
0

我有一个包含数字和日期的表格(1个数字,每个日期和日期不一定是固定的时间间隔)。 我想知道某个数字不在表格中时的日期数。使用子查询结果

我在哪里:

select * 
from 
( 
    select 
    date from nums 
    where chiffre=1 
    order by date desc 
    limit 2 
) as f 

我得到这个:

基本上,我有动态此查询:

select * from nums where date between "2014-07-26" and "2014-09-07" 

,并在第二时间,浏览整个表(因为那里我只限于前2行,但我会比较2和3以及3和4等)。

的目标是得到这样的:

date      | actual_number_of_real_dates_between_two_given_dates 
2014-09-07 - 2014-07-26 |  20 
2014-04-02 - 2014-02-12 |  13 

等等

我怎样才能做到这一点?谢谢。

编辑:

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

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 

等等

编辑2:

我更新的查询感谢戈登·利诺夫

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 

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

回答

0

这是做你想做的吗?

select count(distinct n.date) as numDates, 
     (datediff(dd.d2, dd.d1) + 1) as datesInPeriod, 
     (datediff(dd.d2, dd.d1) + 1 - count(distinct n.date)) as missingDates 
from nums n cross join 
    (select date('2014-07-26') as d1, date('2014-09-07') as d2) d 
where n.date between dd.d1 and dd.d2; 

编辑:

如果你只是想最后两个日期:

select count(distinct n.date) as numDates, 
     (datediff(dd.d2, dd.d1) + 1) as datesInPeriod, 
     (datediff(dd.d2, dd.d1) + 1 - count(distinct n.date)) as missingDates 
from nums n cross join 
    (select min(date) as d1, max(date) as d2 
     from (select date from nums order by date desc limit 2) d 
    ) dd 
where n.date between dd.d1 and dd.d2; 
+0

肯定的,但它缺少动态部分 我想动态生成2014年7月26日和2014- 09-07 谢谢 PS:我只需要“numDates”列;) – sam12 2014-10-27 11:20:27

+0

@ sam12。 。 。只需将你想要的日期添加到子查询中即可。你甚至可以使用'union all'并添加多对日期。 – 2014-10-27 11:34:53

+0

是的,但我不浏览整个表格。我只浏览了最后2个日期(限制2) – sam12 2014-10-27 11:55:40