选择条件后的最后N行

时间:2013-08-15 22:06:24

标签: mysql sql

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

date | status | projectId

状态可以是0或1,主键是日期和projectID

我试图找出自上次为1以来projectID状态为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)

让我难过的是我必须保持约会的顺序。什么是解决这些问题的好方法,尤其是这个问题?

3 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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)

修改

如果在最新状态= 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`)

答案 2 :(得分: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)