select max() 来自 mysql 中不同 ID 的计数结果

select max() from result of count for distinct ids in mysql

我有一个 table 结构如下:

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

基本上我想做的是编写一个查询,其中 returns X 表示 1,因为 X 重复的次数超过 Y(2 次),returns A 表示 2。所以如果一个值出现的次数多于另一个,我的查询应该 return 那个。抱歉,如果标题令人困惑,但我找不到更好的解释。这是我到目前为止尝试过的:

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

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

谢谢

您可以尝试使用 GROUP BY 子句。看到一个Demo Here

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

这应该有效:

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

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

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

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