Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get frequent element of the column in SQL?

I would like to get frequent element of the column in SQL.

For instance,

Assume we have the below column,
Jack
Jack
Jack
Jeremy
Katie
Katie
John

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I would like to get Jack.

Furthermore in below case,
Jack
Jack
Jack
Jeremy
Katie
Katie
Katie
John

I would like to get Jack and Katie.

What I have tried?

GROUP BY COLUMN
ORDER BY COUNT(*) DESC
LIMIT 1;

It works in first case, but since we are limiting it by 1, second case fails and only returns Jack instead of Jack and Katie.

TL;DR I would like to get most frequent elements even if their frequency are the same.

Thanks in advance.

>Solution :

You can try to use HAVING subquery

SELECT name,COUNT(*) cnt
FROM T
GROUP BY name
HAVING COUNT(*) = (
  SELECT COUNT(*) cnt
  FROM T
  GROUP BY name
  ORDER BY COUNT(*) DESC
  LIMIT 1
)

if your MySQL version support the window function, you can try this.

SELECT *
FROM (
  SELECT *,dense_rank() over(order by cnt desc) rn 
  FROM (
   SELECT *,COUNT(*) OVER(PARTITION BY name) cnt
   FROM T
  ) t1
) t1
WHERE rn = 1

sqlfiddle

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading