So I can’t remember how exactly I can show all groups with MAX/MIN ppl in them. Say there is a table with columns Id, name, role(employee, employer), groupName(a1, b2, c3…) and I need to list MAX/MIN number of the employees in each group.
SELECT `groupName`, COUNT(*)
FROM Table1
WHERE ROLE = 'employee'
GROUP BY `groupName`
ORDER BY COUNT(*) DESC;
I need to find MAX/MIN number of employees in each group and there is a lot of groups.
But I guess what I really wonder is how can you select only maximum count and minimum count. Say in group 1a there is 200 employees and in 2b, 3c there is only one employee. Of course there is other groups but they are somewhere in between, and I need to get in my report only MAX and only MIN.
2
Answers
If you want the count for each group, you can do the following:
The
MIN
orMAX
only makes sense to use when you’re actually finding the min and max of a numerical column (or date, etc.). If you want to count employees per group, you can just useCOUNT
.If you need to show the group whose count is the maximum (or minimum) of all the groups, this is a slightly different question.
If you really want to find the maximum number of employees for each group indeed, then the question does not make sense, because each group has a single number of employees (ex. group1 has 6 employees, group2 has 3 employees, etc.). So, in this answer I will presume that you want the minimum employee number and maximum employee number of each group.
If you want to get the min/max employee number in each group, then you can achieve this as below: