我有一个包含数字和日期的表格(每个日期和日期不一定是固定间隔的1个数字)。 我希望得到一个数字不在表中的日期计数。
我在哪里:
select *
from
(
select
date from nums
where chiffre=1
order by date desc
limit 2
) as f
我明白了:
date
--------------
2014-09-07
--------------
2014-07-26
基本上,我动态地进行了这个查询:
select * from nums where date between "2014-07-26" and "2014-09-07"
并且第二次浏览整个表格(因为我限制了前两行,但我会比较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:
感谢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? 我应该使用循环吗?或者我可以不用吗?
答案 0 :(得分: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;