简体   繁体   中英

How to sort SQL query by if statement

I got two tables that look like this:

STUDENT
ID:Integer
NAME: String
GENDER: Character
DEPT_ID: Integer

DEPARTMENT
ID: Integer
NAME: String

I want to write a query to print the respective department name and number of students majoring in each department for all departments in the Department table (even ones with no current students).

My goal is to sort the results by descending number of student; if 2 or more students have the same number of students, then sort those departments alphabetically by department name.

SELECT DEPARTMENT.NAME, COUNT (STUDENT.ID) AS STUDENT_COUNT FROM DEPARTMENT LEFT JOIN STUDENT ON DEPARTMENT.ID = STUDENT.DEPT_ID GROUP BY DEPARTMENT.NAMR ORDER BY STUDENT-COUNT DESC;

I'm quite new to SQL but this is the best I could come up with. It's not sorting the departments with same name alphabetically.

您可以像这样在学生人数后添加部门名称

SELECT DEPARTMENT.NAME, COUNT (STUDENT.ID) AS STUDENT_COUNT FROM DEPARTMENT LEFT JOIN STUDENT ON DEPARTMENT.ID = STUDENT.DEPT_ID GROUP BY DEPARTMENT.NAME ORDER BY STUDENT-COUNT DESC,DEPARTMENT.NAME;
SELECT DEPARTMENT.NAME, COUNT(STUDENT.ID) AS STUDENT_COUNT 
FROM DEPARTMENT 
LEFT JOIN STUDENT 
ON DEPARTMENT.ID = STUDENT.DEPT_ID 
GROUP BY DEPARTMENT.NAME 
ORDER BY STUDENT_COUNT DESC,DEPARTMENT.NAME ASC;

Below is the link to sqlfiddle with example.

Link: http://sqlfiddle.com/#!9/08807c4/1/0

Resultset

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