Mysql每组最大计数

时间:2015-08-13 09:46:59

标签: mysql count max

我有下表:

+---------+--------+-------+
| client  | session| boat  |
+---------+--------+-------+
|       1 |   1943 |     3 |
|       1 |   1943 |     4 |
|       1 |   1944 |     3 |
|       1 |   1944 |     4 |
|       1 |   1945 |     4 |
|       2 |   1944 |     3 |
|       2 |   1944 |     4 |
|       3 |   1944 |     3 |
+---------+--------+-------+

我想得到船的最大数量,然后我这样做了:

SELECT boat,session,max(counter) as max_boats FROM (SELECT boat,COUNT(boat) as counter,session FROM `test` GROUP BY boat,session) as cont2 GROUP BY boat

结果:

+------+---------+-----------+
| boat | session | max_boats |
+------+---------+-----------+
|    3 |    1943 |         3 |
|    4 |    1943 |         2 |
+------+---------+-----------+

所以,我的问题是这个查询返回“session = 1943”,这是错误的。正如你在原始表中看到的那样,3号船有三排,但有1944号会议,4号船有两段会议,但也有1944号会议。

问题是,当我做max(计数器)时,MySQL会返回第一个会话,而不是与max(counter)对应的行。

也许我的方法是错误的,整个查询都是错误的。

感谢您的回答。

解决方案是:

+------+---------+-----------+
| boat | session | max_boats |
+------+---------+-----------+
|    3 |    1944 |         3 |
|    4 |    1944 |         2 |
+------+---------+-----------+

3 个答案:

答案 0 :(得分:1)

以下是获取此功能的一种方法,这可能不是最好的方法,您也可以查看其他选项。

select 
x.boat, 
x.session, 
max_boats
from (
  select 
  boat, 
  session, 
  count(*) cnt
  from boats
  group by boat, session
)x
join(
  select boat, 
  max(cnt) max_boats
  from(
    select 
    boat, 
    session, 
    count(*) cnt
    from boats
    group by boat, session
  )y
  group by boat
)t on x.boat = t.boat and x.cnt = t.max_boats

答案 1 :(得分:0)

这有用吗?

SELECT COUNT(*) AS `max_boats`, `session` FROM `boats` GROUP BY `session` ORDER BY COUNT(*) DESC

<强>输出:

+-----------+---------+
| max_boats | session |
+-----------+---------+
|         5 |    1944 |
|         2 |    1943 |
|         1 |    1945 |
+-----------+---------+

您可以使用LIMIT 1

将输出限制为第一个
SELECT COUNT(*) AS `max_boats`, `session` FROM `boats` GROUP BY `session` ORDER BY COUNT(*) DESC

<强>输出:

+-----------+---------+
| max_boats | session |
+-----------+---------+
|         5 |    1944 |
+-----------+---------+

小提琴:http://sqlfiddle.com/#!9/59e53/3

答案 2 :(得分:0)

试试这个!

SELECT COUNT(*), client, session
FROM `test` 
GROUP BY client, session
ORDER BY COUNT(*) DESC
LIMIT 1

:)