2

我有一个包含 3 列的日志的数据库表:

date | status | projectId

status 可以是 0 或 1,主键是 on date 和 projectID

我试图找出一个 projectID 自上次为 1 以来状态为 0 的次数。

所以如果只有一个 projectId

date | status | projectId
  1       0        3
  2       0        3
  3       1        3
  4       1        3
  5       0        3
  6       0        3

这应该返回 2(第 5 行和第 6 行是 0,第 4 行是 1)

让我感到困难的是我必须保持日期的顺序。什么是解决此类问题的好方法,尤其是这个问题?

4

3 回答 3

4

以下是您为一个项目执行此操作的方法:

select count(*)
from logs l
where status = 0 and
      projectid = 3 and
      date > (select max(date) from logs where projectid = 3 and status = 1)

以下是您将如何为所有项目执行此操作:

select l.projectId, count(l1.projectId)
from logs l left outer join
     (select projectId, max(date) as maxdate
      from logs
      where status = 1
      group by projectId
     ) l1
     on l.projectId = l1.projectId and
        l.date > l1.date and
        l.status = 0
group by l.projectId;
于 2013-08-15T22:13:11.593 回答
0

这是获取所有 project_id 的结果的一种方法:

SELECT m.project_id
     , COUNT(1) AS mycount
  FROM ( SELECT l.project_id
              , MAX(l.date) AS latest_date
           FROM mytable l
          WHERE l.status = 1
       ) m
  JOIN mytable t
    ON t.project_id = m.project_id 
   AND t.date > m.latest_date
   AND t.status = 0

如果您只需要 project_id 的子集,则应将谓词添加到内联视图查询的 WHERE 子句中:

          WHERE l.status = 1
            AND l.project_id IN (3,5,7)

编辑

如果在最新的 status=1 行之后没有 status=0 行,则该查询不会返回一行。要返回零计数,可以使用外连接来完成。

SELECT m.project_id
     , COUNT(t.status) AS mycount
  FROM ( SELECT l.project_id
              , MAX(l.date) AS latest_date
           FROM mytable l
          WHERE l.status = 1
            AND l.project_id IN (3)
       ) m
  LEFT
  JOIN mytable t
    ON t.project_id = m.project_id 
   AND t.date > m.latest_date
   AND t.status = 0

为了获得最佳性能,该语句可以使用具有project_iddate(按该顺序)的前导列并包括该status列的索引,例如

ON mytable (`project_id`,`date`,`status`)
于 2013-08-15T22:18:20.470 回答
0

在这里,您只有一个选择。

http://sqlfiddle.com/#!2/6ce87/11

select *
from logs
where status=0 and date > (select date from logs where status=1 order by date desc limit 1)
于 2013-08-15T22:20:34.257 回答