从mysql中不同id的count计数结果中选择max()

时间:2015-08-04 20:30:03

标签: mysql max

我有一个具有以下结构的表:

id    name
1     X
1     X
1     Y
2     A
2     A
2     B

基本上我要做的是编写一个返回X为1的查询,因为X重复超过Y(2次)并返回A为2.所以如果一个值出现的次数超过另一个我的查询应该归还那个。很抱歉,如果标题令人困惑,但我找不到更好的解释。这是我到目前为止所尝试的:

SELECT MAX(counted) FROM(
    SELECT COUNT(B) AS counted
    FROM table
    GROUP BY A
) AS counts;

问题是我的查询应该返回除计数之外的实际值。

由于

3 个答案:

答案 0 :(得分:3)

这应该有效:

SELECT count(B) as occurrence, A, B
FROM table
GROUP BY B 
ORDER BY occurrence DESC
LIMIT 1;

请检查:http://sqlfiddle.com/#!9/dfa09/3

答案 1 :(得分:0)

您可以使用GROUP BY子句尝试这样做。查看Demo Here

select *, max(occurence) as Maximum_Occurence from
(
select B, count(B) as occurence
from table1
group by B
) xxx

答案 2 :(得分:0)

这就是我最终解决问题的方法。不是最有效的方式,但完成工作:

select A,B from 
(select A,B, max(cnt) from 
(select A ,B ,count(B) as cnt 
    from myTable 
    group by A,B 
    order by cnt desc
) as x group by A
) as xx