-1

I am stuck in a query, my query is as follow:

SELECT department_name AS 'Department Name', COUNT(*) AS 'No of Employees' FROM departments INNER JOIN employees ON employees.department_id = departments.department_id GROUP BY departments.department_id, department_name
ORDER BY COUNT(*) DESC;

this query is giving me results as in below attachment

enter image description here

What i want now is to sort the departments alphabetically if two or more department have same number of students. e.g "Purchasing" and "Finance" should be sort alphabetically.

You can try this query in the following link:

Check your query here

Muhammad Qasim
  • 1,622
  • 14
  • 26
Ammar Ahmed
  • 126
  • 8

2 Answers2

1

This is simple. You can order by your result set by multiple columns as follows:

 SELECT department_name AS 'Department Name', COUNT(*) AS 'No of Employees'
 FROM departments INNER JOIN employees ON 
 employees.department_id = departments.department_id 
 GROUP BY departments.department_id, department_name
 ORDER BY COUNT(*) DESC, department_name Asc;

The following thread is a good read

SQL Multiple Column Ordering

Hope this helps :)

Community
  • 1
  • 1
Muhammad Qasim
  • 1,622
  • 14
  • 26
0

Is this what you are looking for.?

    SELECT department_name AS 'Department Name', COUNT(*) AS 'No of Employees' 
    FROM departments INNER JOIN employees ON employees.department_id = departments.department_id GROUP BY departments.department_id, department_name
    ORDER BY department_name,COUNT(*) DESC;
Mahesh.K
  • 901
  • 6
  • 15