我需要一个SQL,我得到的ID比其他的更多......但我需要id而不是计算它创建id的频率......
post | id
==============
hello | 2
guys | 1
how | 2
are | 2
它应该给我“2”。
感谢您的帮助。
答案 0 :(得分:1)
SELECT COUNT(*) AS cnt, id
FROM <table>
GROUP BY id
ORDER BY cnt DESC
LIMIT 1
答案 1 :(得分:0)
你正在寻找的是什么叫做MODE,我做了类似的事情 Is there a simpler way to find MODE(S) of some values in MySQL
对于有多于1种模式的情况(例如,id 2出现3次而id 1也出现3次)(sqlFiddle) 您可以使用以下查询之一
这个将以逗号分隔列表的形式返回id 1和2(当然,您必须用实际的表名替换yourTable
)
SELECT GROUP_CONCAT(CASE WHEN occurs=@maxoccurs THEN value ELSE NULL END) as modes
FROM
(SELECT value,occurs,@maxoccurs:=GREATEST(@maxoccurs,occurs) as maxoccurs
FROM (SELECT id as value,count(*) as occurs
FROM yourTable
GROUP BY id)T1,(SELECT @maxoccurs:=0)mo
)T2;
这个将返回id 1和2作为2个单独的行
SELECT value as id FROM
(SELECT value,occurs,@maxoccurs as maxoccurs
FROM
(SELECT value,occurs,@maxoccurs:=GREATEST(@maxoccurs,occurs) as maxoccurs
FROM (SELECT id as value,count(*) as occurs
FROM yourTable
GROUP BY id)T1,(SELECT @maxoccurs:=0)mo
)T2
)T3
WHERE occurs = maxoccurs