我有一个包含以下列的表:id、name、date、present 当前列的值为 0 或 1 或 2 以及...更多 我需要统计当月 2013-07-01 - 2013-07-31 有多少个 0 值,但仅当有或超过 10 次时才计数。
例如,如果我有 2013-07-01 到 2013-07-10 值 0 它应该计算它并让我知道这是 10 个或更多连续天,例如 11、12 或更多,但如果它小于 10 则不应计算任何内容。
我正在尝试堆栈中的一些示例...但它们是不同的问题...所以我在该 mysql 查询方面需要很少的帮助。
我有这样的东西,但需要连续 10 天,例如 >= 10
$sql = mysql_query("SELECT COUNT(name) as count FROM `table` WHERE (`present` = 0) AND (`date` BETWEEN '2013-07-01' AND '2013-07-31')");
while($row = mysql_fetch_array($sql)){
$result = $row['count'];
}
它对 2013-07-01 和 2013-07-31 之间的日期中的每 0 个值进行计数,但我需要计算从 10 个或更多连续天开始的天数
当前列有 0 和其他数字,如 1、2、3...,所以我只需要计算连续 10 天或更多天的 0
这是 SqlFiddle 我试图从答案中发出警告 http://sqlfiddle.com/#!2/1bde8/2
最诚挚的问候 米。
最佳答案
此方法使用相关子查询来计算两个值。
第一个值是上一条记录的日期,其中 Present = 1
。这样您就可以使用 datediff()
获取 Present = 0
的连续天数。
第二个是明天的当前
值,该值在该月的最后一天将为NULL
。当今天有 Present = 0
而明天是 1
或 NULL
时,我们就可以使用这条记录。它是 0
序列的结尾。
接下来的问题就是根据您设置的条件将值相加。以下查询假设您要对每个 name
执行此操作:
select name, sum(case when datediff(date, lastPresentDate) >= 10
then datediff(date, lastPresentDate)
else 0 end) as DaysCounted
from (select t.*,
(select coalesce(max(date), '2013-06-30')
from t t2
where t2.name = t.name and
t2.present <> 0 and
t2.date <= t.date and
t2.date between '2013-07-01' and '2013-07-31'
) as lastPresentDate,
(select t2.present
from t t2
where t2.name = t.name and
t2.date = adddate(t.date, 1)
order by t2.date
limit 1
) as TomorrowPresent
from t
where date between '2013-07-01' and '2013-07-31'
) t
where Present = 0 and (TomorrowPresent = 1 and TomorrowPresent is null)
group by name
关于mysql - 如何计算连续10天的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17641191/