我有表格列:id,name,date,present 列存在的值为0或1或2且更多 我需要计算2013-07-01 - 2013-07-31当月有多少0有价值,但只有当有或超过10次才算数。
例如,如果我有 2013-07-01至2013-07-10 valoues 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 ...所以我需要只计数0连续10天或更多
这里是SqlFiddle我试图从答案中获胜 http://sqlfiddle.com/#!2/1bde8/2
最好的问候 米。答案 0 :(得分:2)
此方法使用相关子查询来计算两个值。
第一个值是上一个记录Present = 1
的日期。这样,您就可以使用Present = 0
获取datediff()
行中的天数。
第二个是明天的Present
值,在该月的最后一天为NULL
。如果今天有Present = 0
,明天有1
或NULL
,那么我们就可以使用此记录。它是0
s。
从这里只是根据您设置的条件添加值的问题。以下查询假定您要为每个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
答案 1 :(得分:0)
此查询仅在10或大于10时才会计算。
SELECT COUNT(`name`) as `count`
FROM `table`
WHERE (`present` = 0)
AND (`date` BETWEEN '2013-07-01' AND '2013-07-31')
HAVING `count` >= 10;
希望它有所帮助!
答案 2 :(得分:0)
未经测试,但您可以使用以下用户变量: -
SELECT SUM(if(ConsCounter=10, 1, 0))
FROM
(
SELECT id, name, date, present, @Counter := IF(@PrevPresent = present AND present = 0, @Counter + 1, 0) AS ConsCounter, @PrevPresent = present
FROM
(
SELECT id, name, date, present
FROM `table`
ORDER BY date
) Sub1
CROSS JOIN (SELECT @PrevPresent:=-99999, @Counter:=0) Sub2
) Sub4
按日期顺序获取所有记录,并为计数添加序列号,因为当前为0.然后计算计数器为10的次数。