编写查询以显示学生人数最多的部门名称

时间:2019-04-17 15:42:12

标签: oracle

this is the schema 编写查询以显示学生人数最多的部门的名称。

这是尝试的。

select d.department_name,count(s.student_id)
     from department d left join student s
     on d.department_id=s.department_id 
     group by d.department_name,d.department_id
     order by d.department_name;

我认为我的代码中缺少一些东西

3 个答案:

答案 0 :(得分:0)

您快到了。
按照学生人数的降序排列结果,然后进行第一行:

SELECT department_name
FROM
(
  SELECT   d.department_name,
           COUNT(*) AS nr_students
  FROM     department d
  JOIN     student    s
    ON     d.department_id = s.department_id
  GROUP BY d.department_name
  ORDER BY nr_students DESC
)
WHERE ROWNUM <= 1;

答案 1 :(得分:0)

基于上述架构,您必须从人员表中对部门表进行联接(INNER JOIN)才能获得部门名称。

如果不需要部门名称,并且计数仅基于department_id,则不需要联接。

下面提到了两种情况的查询。

Oracle SQL查询部门名称(即INNER JOIN)的结果

SELECT D.DEPARTMENT_NAME, COUNT(S.DEPARTMENT_ID) AS STAFF_COUNT FROM **DEPARTMENT D, STAFF S** --INDICATES INNER JOIN IN ORACLE SQL
WHERE D.DEPARTMENT_ID = S.DEPARTMENT_ID
GROUP BY D.DEPARTMENT_NAME
ORDER BY STAFF_COUNT DESC

Oracle SQL查询结果,不包含部门名称,仅显示部门编号

SELECT S.DEPARTMENT_ID,COUNT(S.DEPARTMENT_ID) AS STAFF_COUNT FROM STAFF S
GROUP BY S.DEPARTMENT_ID
ORDER BY STAFF_COUNT DESC

希望这会有所帮助。干杯。

答案 2 :(得分:0)

我试过了,它奏效了。

select department_name 
from department d inner join student s 
on s.department_id=d.department_id 
having count(*) in (
    select max(count(student_id)) 
    from student s join department d 
    on d.department_id=s.department_id 
    group by d.department_id)
group by d.department_id,department_name;