Skip to content
Advertisement

How to find the Group with the Max value

I have a database of students, I have to group them by their class and then find out which class has the most students. I know it’s probably a stupid question but I can’t come to the solution.

Sample data:

| Name | Class |
|------|-------|
|Tony| 4|
|Anna| 5|
|John| 4|

The output should show class number 4 has the most students

Advertisement

Answer

If you want one row, then you can use:

select class, count(*)
from students
group by class
order by count(*) desc
fetch first 1 row only;

This uses standard SQL functionality. Your database may ahve some other method for choosing one row, such as limit 1 or select top (1).

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement