尝试显示学生人数最少的部门的名称。
尝试这样的事情:
SELECT TOP 1 department_name, count(*) AS number_of_students
FROM department natural join student
GROUP BY department_name
ORDER BY number_of_students
它将为您提供按学生人数排序的部门列表。通过仅通过TOP 1
选择第一行,您将只获得学生人数最少的部门。
是这样的吗?
SELECT
T1.department_name, COUNT(T2.department_id) totalCount
FROM department T1
LEFT JOIN student T2
ON T1.department_id = T2.department_id
GROUP BY T2.department_id
HAVING COUNT(T2.department_id) =
(
SELECT
COUNT(T2.department_id) totalCount
FROM department T1
LEFT JOIN student T2
ON T1.department_id = T2.department_id
GROUP BY T2.department_id
ORDER BY totalCount ASC
LIMIT 1
)
SQLFIDDLE 演示