简体   繁体   中英

Maximum Count of Distinct Values in SQL

please forgive me if this has been answered, but could not find it using the search tool or a basic google query.

I am trying to return a value that indicates the maximum number of rows any distinct value in a column in SQL.

For example, I'd like to use something like

SELECT MAX(COUNT(DISTINCT person_id) AS MAX_NUM_PERS_ROW
FROM mytable

and if the person with most rows in the table had 5 rows, the value returned would be 5...

Any and all help is appreciated!

You can do this with nested aggregation:

select max(cnt)
from (select person_id, count(*) as cnt
      from mytable
      group by person_id
     ) p;

If you actually want the person, you can also do:

select person_id, count(*) as cnt
from mytable
group by person_id
order by count(*) desc
limit 1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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