0

我有包含列的表:id、name、date、present 列存在的值为 0 或 1 或 2 并且...更多我需要计算当前月份 2013-07-01 - 2013-07-31 中有多少 0 valous但仅在有或超过 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

这是我试图从答案http://sqlfiddle.com/#!2/1bde8/2中得到的 SqlFiddle

最好的问候米。

4

3 回答 3

2

这种方法使用相关子查询来计算两个值。

第一个值是上一条记录的日期,其中Present = 1。这使您可以Present = 0使用datediff().

第二个是Present明天的值,它将NULL在该月的最后一天。当今天有Present = 0并且明天是或者1或者NULL时,那么我们可以使用这个记录。它是0s 序列的结尾。

从那里只是根据您设置的条件将值相加的问题。以下查询假定您要对每个 执行此操作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
于 2013-07-14T16:39:13.560 回答
0

Not tested, but you could use user variables like this:-

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

Get all the records in date order and add a sequence number for the count since the present was first 0. Then count the number of times that counter is 10.

于 2013-07-14T21:15:56.503 回答
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;

希望能帮助到你!

于 2013-07-14T17:04:59.383 回答