Sql 有没有办法缩短下面的代码?

Sql 有没有办法缩短下面的代码?,sql,join,subquery,Sql,Join,Subquery,问题:编写查询以显示学生人数最少的系的名称。根据部门名称按升序对结果进行排序 我的代码: 选择部门名称 从d系加入学生s 在d.department\u id=s.department\u id上 在选择mincountstudent\u id中有count* 从学生处加入d系 在s.department\u id=d.department\u id上 按d.部门编号分组 按部门名称分组 按部门名称排序; 注: 学生,系里是分开的桌子 部门id是部门表中的主键 部门id是学生表中的外键 代码工作

问题:编写查询以显示学生人数最少的系的名称。根据部门名称按升序对结果进行排序

我的代码:

选择部门名称 从d系加入学生s 在d.department\u id=s.department\u id上 在选择mincountstudent\u id中有count* 从学生处加入d系 在s.department\u id=d.department\u id上 按d.部门编号分组 按部门名称分组 按部门名称排序; 注: 学生,系里是分开的桌子 部门id是部门表中的主键 部门id是学生表中的外键
代码工作得非常好,只需要缩短它。

我会使用一个窗口函数:

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。

hi,不需要该图像,您可以格式化代码,只需将其缩进4个空格,然后将其转换为代码您使用的是什么数据库?我不相信该代码可以完美工作,因为它是无效的标准SQL-需要分组