1

For example, we have 1, 2 and 3 are the most frequent values at the same time, how to return them when it is a tie?

id
1
1
1
2
2
2
3
3
3
4
Radim Bača
  • 10,646
  • 1
  • 19
  • 33
Mor_Poi
  • 11
  • 1

1 Answers1

2

You could try:

SELECT id
FROM yourTable
GROUP BY id
HAVING COUNT(*) = (SELECT COUNT(*) FROM yourTable
                   GROUP BY id ORDER BY COUNT(*) DESC LIMIT 1);

On more recent versions of MySQL 8+, we can use RANK here:

WITH cte AS (
    SELECT id, RANK() OVER (ORDER BY COUNT(*) DESC) rnk
    FROM yourTable
    GROUP BY id
)

SELECT id
FROM cte
WHERE rnk = 1;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360