简体   繁体   English

SQL-经常出现的值

[英]SQL - Value that appears often

I need a SQL where I get the id that's appears many more than the other ... But I need the id and not the count how often it founded the id ... 我需要一个SQL,使我得到的ID比其他ID多得多……但是我需要ID,而不是计数它建立ID的频率……

post    | id 
==============
hello   | 2
guys    | 1
how     | 2
are     | 2

It should give me "2" back. 它应该给我“ 2”。

Thanks for your help. 谢谢你的帮助。

SELECT COUNT(*) AS cnt, id
FROM <table>
GROUP BY id
ORDER BY cnt DESC
LIMIT 1

what you're looking for is called the MODE, i have done a similar thing Is there a simpler way to find MODE(S) of some values in MySQL 您正在寻找的被称为MODE,我做了类似的事情是否有更简单的方法来找到MySQL中某些值的MODE(S)

for cases where there is more than 1 mode (for example, id 2 occurs 3 times and id 1 also occurs 3 times) ( sqlFiddle ) you can use one of the queries below 对于模式不止一种的情况(例如,id 2发生3次,并且id 1也发生3次)( sqlFiddle ),可以使用以下查询之一

this one will return id 1 and 2 as a comma separated list (you have to replace yourTable with your actual table name of course) 此表将返回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;

this one will return id 1 and 2 as 2 separate rows 这将返回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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM