微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

php – 根据mySQL中的COUNT()值限制GROUP BY

我正在将事件记录到MysqL数据库中,并希望获得前3个事件用于监视目的.

我的表事件日志如下所示:

+----+------------------+---------------------+
| id |    eventname     |      eventdate      |
+----+------------------+---------------------+
|  0 | machine1.started | 2016-09-04 19:22:23 |
|  1 | machine2.reboot  | 2016-09-04 20:23:11 |
|  2 | machine1.stopped | 2016-09-04 20:24:12 |
|  3 | machine1.started | 2016-09-04 20:25:12 |
|  4 | machine1.stopped | 2016-09-04 23:23:16 |
|  5 | machine0.started | 2016-09-04 23:24:00 |
|  6 | machine1.started | 2016-09-04 23:24:16 |
|  7 | machine3.started | 2016-09-04 23:25:00 |
|  8 | machine4.started | 2016-09-04 23:26:00 |
|  9 | cluster.alive    | 2016-09-04 23:30:00 |
| 10 | cluster.alive    | 2016-09-05 11:30:00 |
+----+------------------+---------------------+

查询最终应返回以下内容,持有

>最常发生的前3个事件(基于MysqL的COUNT()函数生成的列事件计数),按事件名称分组
>只有2行,其中eventcount = 1,但仅当1位于前3个事件计数内时(因为有很多事件发生在
一次,因此会超载我的前端)

基于上表的所需结果示例:

+------------+------------------+
| eventcount |    eventname     |
+------------+------------------+
|          3 | machine1.started |
|          2 | machine1.stopped |
|          2 | cluster.alive    |
|          1 | machine0.started |
|          1 | machine2.started |
+------------+------------------+

请注意,我不需要仅返回3行,而是具有3个最高事件数量的行.

我通过搞乱下面的查询字符串进行了大量的实验,包括多个选择和可疑的CASE … WHEN条件,但是无法使其按照我需要的方式工作.

SELECT COUNT(id) AS 'eventcount',eventname
FROM eventlog
GROUP BY eventname
ORDER BY eventcount DESC;

以高效的方式获得理想结果的最佳方法是什么?

最佳答案
这是使用变量的一种方法
sql小提琴:http://sqlfiddle.com/#!9/b3458b/16

SELECT
  t2.eventcount,t2.eventname
FROM
(
  SELECT
      t.eventname,t.eventcount,@Rank:=IF(@PrevCount=t.eventcount,@Rank,@Rank+1) Rank,@CountRownum:=IF(@PrevCount=t.eventcount,@CountRowNum + 1,1) CountRowNum,@PrevCount:= t.eventcount
    FROM
      (
        SELECT
          l.eventname,COUNT(*) as eventcount
        FROM
          eventlog l
        GROUP BY
          l.eventname
        ORDER BY
          COUNT(*) DESC
      ) t
      CROSS JOIN (SELECT @Rank:=0,@CountRowNum:=0,@PrevCount:=-1) var
    ORDER BY
      t.eventcount DESC
) t2
WHERE
  t2.Rank < 4
  AND NOT (t2.eventcount = 1 AND t2.CountRowNum > 2)

原文地址:https://www.jb51.cc/mysql/432871.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐