问题:编写查询以显示学生人数最少的部门的名称。根据部门名称升序对结果进行排序
我的代码:
select department_name
from department d join student s
on d.department_id=s.department_id
having count(*) in (select min(count(student_id))
from student s join department d
on s.department_id=d.department_id
group by d.department_id)
group by department_name
order by department_name;
注意:
Student
,Department
是单独的表
department_id
是Department
表中的主键
department_id
是Student
表中的ForeignKey
代码运行完美(只是需要缩短它)。
答案 0 :(得分:0)
我会为此使用一个窗口函数:
select d.*
from (
select s.department_id,
count(*) as student_count,
dense_rank() over (order by count(*)) as rnk
from student s
group by s.department_id
) as c
join department d on d.department_id = c.department_id
where c.rnk = 1
order by d.department_name;
如果需要,还可以在输出中包括实际的学生人数。
以上仅包括有学生的部门。如果您需要照顾没有分配学生的部门,则需要外部加入:
select d.department_name
from (
select d.department_name,
count(s.student_id) as student_count,
dense_rank() over (order by count(s.student_id)) as rnk
from department d
left join student s on s.department_id = d.department_id
group by d.department_name
) d
where d.rnk = 1;
这两种解决方案都是100%标准的ANSI SQL,并且可以在任何现代DBMS上使用。