Search code examples
sqloracle-sqldeveloper

How do I display rows from a max count?


I want to return all the data, from max count query with hospital that has most number of patients. What I seem to be getting when I try to nest queries is display of all rows of hospital data. I've tried to look at similar questions in stack overflow and other sites it seems to be a simple query to do but i am not getting it.

select max(highest_hospital) as max_hospital
from (select count(hospital) as highest_hospital
from doctor
group by hospital)

highest_hospital
-------------
            3

Doc ID  Doctor           Patient               Hospital    Medicine   Cost
------ -------           ------            ---------      ------     --------
1      Jim Bob         Patient1             Town 1        Medicine 1   4000
2      Janice Smith    Patient2             Town 2        Medicine 3    3000
3      Harold Brown    Patient3             Town 2        Medicine 5    2000
4      Larry  Owens    Patient4             Town 2        Medicine 6    3000
5      Sally Brown     Patient5             Town 3        Medicine 7    4000
6      Bob Jim         Patient6             Town 4        Medicine 8     6000

Outcome should be return of 3 rows

Doc ID  Doctor           Patient               Hospital    Medicine   Cost
------ -------           ------            ---------      ------     --------
2      Janice Smith    Patient2             Town 2        Medicine 3    3000
3      Harold Brown    Patient3             Town 2        Medicine 5    2000
4      Larry  Owens    Patient4             Town 2        Medicine 6    3000

Solution

  • You can use window functions:

    select d.*
    from (select d.*, max(hospital_count) over () as max_hospital_count
          from (select d.*, count(*) over (partition by hospital) as hospital_count
                from doctor d
               ) d
         ) d
    where hospital_count = max_hospital_count;
    

    Edit:

    Using GROUP BY is a pain. If you are only looking for a single hospital (even when there are ties), then in Oracle 12C you can do:

    select d.*
    from doctor d
    where d.hospital = (select d2.hospital
                        from doctor d2
                        group by d2.hospital
                        order by count(*) desc
                        fetch first 1 row only
                       );
    

    You can do this in earlier versions of Oracle using an additional subquery.