如何在SQL中找到所有最常见的值?

时间:2014-06-18 04:11:14

标签: mysql sql count popularity

我如何在SQL中显示所有最常见的值?

所以我有查询在下面显示最常见的值。

SELECT name, COUNT(*) AS popularity
FROM cattwo 
GROUP BY name 
ORDER BY popularity DESC 
LIMIT 1;

    +----------+------------+
    | name     | popularity |
    +----------+------------+
    | cat22610 |          7 |
    +----------+------------+

但是,当我显示前10个最常见的值时,结果是......

SELECT name, COUNT(*) AS popularity 
FROM cattwo 
GROUP BY name 
ORDER BY popularity DESC 
LIMIT 10;

    +----------+------------+
    | name     | popularity |
    +----------+------------+
    | cat22610 |          7 |
    | cat68704 |          7 |
    | cat14153 |          7 |
    | cat52476 |          7 |
    | cat4556  |          7 |
    | cat64173 |          7 |
    | cat5586  |          7 |
    | cat89302 |          6 |
    | cat97131 |          6 |
    | cat42010 |          6 |
    +----------+------------+

目标是展示所有受欢迎程度最高的猫。像这样的东西。

+----------+------------+
| name     | popularity |
+----------+------------+
| cat22610 |          7 |
| cat68704 |          7 |
| cat14153 |          7 |
| cat52476 |          7 |
| cat4556  |          7 |
| cat64173 |          7 |
| cat5586  |          7 |
+----------+------------+

帮助会很棒。提前致谢。

3 个答案:

答案 0 :(得分:1)

SELECT name, COUNT(*) AS popularity 
FROM cattwo 
GROUP BY name 
HAVING COUNT(*) = 
        (
            SELECT COUNT(*) AS popularity 
            FROM cattwo 
            GROUP BY name
            ORDER BY popularity DESC
            LIMIT 1
        )
LIMIT 10;

答案 1 :(得分:1)

我想这个查询可以帮到你!

SELECT NAME, COUNT(*) AS POPULARITY 
FROM CATTWO 
GROUP BY NAME 
HAVING COUNT(*) = 
        (
            SELECT COUNT(*) AS MAX_POPULARITY 
            FROM CATTWO 
            GROUP BY NAME
            ORDER BY MAX_POPULARITY DESC
            LIMIT 1
        );

答案 2 :(得分:0)

select C1.name,COUNT(*) AS  popularity FROM cattwo C1 GROUP BY C1.name

HAVING 0=(SELECT COUNT(*) popularity  FROM  cattwo 
C2 GROUP BY C2.NAME HAVING C1.popularity <C2.popularity )