通过MySQL中每个组的最后N行获取状态

通过MySQL中每个组的最后N行获取状态,mysql,sql,Mysql,Sql,以下是简化表格: 我需要在最后N行中获取每组失败的结果信息。 这样N=3: group has_failures ------ ------------ group1 1 group2 0 group3 0 获取组非常容易: -- Select last row from each group: SELECT a.id, a.group, a.status FROM log a INNER JOIN( select max(i.id) as max_id fro

以下是简化表格:

我需要在最后N行中获取每组失败的结果信息。 这样N=3:

group   has_failures
------  ------------
group1  1
group2  0
group3  0
获取组非常容易:

-- Select last row from each group:
SELECT a.id,  a.group, a.status
FROM log a
INNER JOIN(
    select max(i.id) as max_id 
    from log i
    group by i.group
) as b on a.id = b.max_id;
还有失败:

-- Select fail status by last 3 rows:
select count(g.status) > 0 as has_failures
from (
       SELECT a.group, a.status
       FROM log a
       WHERE a.group = 'group3'
       ORDER BY id DESC
       LIMIT 3
     ) as g
where g.status = 'fail';
这两个查询应该如何合并,或者更简单的方法是如何存在的?

这里有一个选项,使用用户定义的变量来建立每个组的行号。然后可以使用条件聚合:


您的group3行的has_failures不应该等于1吗?不,因为group3 ID 6、7、8的最后3个条目成功了。好的,那么我的答案无效。不知道你只考虑了最后3个条目。。。
-- Select fail status by last 3 rows:
select count(g.status) > 0 as has_failures
from (
       SELECT a.group, a.status
       FROM log a
       WHERE a.group = 'group3'
       ORDER BY id DESC
       LIMIT 3
     ) as g
where g.status = 'fail';
select max(t.id) id,
  t.group,
  max(case when t.rank = 1 then t.status end) status,
  sum(case when t.status = 'fail' then 1 else 0 end) hasfailures
from (
  select *, 
    case l.group 
      when @curGroup 
      then @curRow := @curRow + 1 
      else @curRow := 1 AND @curGroup := l.group 
    end + 1 AS rank
  from `log` l cross join (select @curRow:=0, @curGroup:='') c
  order by l.group, id desc
  ) t
where rank <= 3
group by t.group