我有一个具有以下结构的表:
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;
问题是我的查询应该返回除计数之外的实际值。
由于
答案 0 :(得分:3)
这应该有效:
SELECT count(B) as occurrence, A, B
FROM table
GROUP BY B
ORDER BY occurrence DESC
LIMIT 1;
答案 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