编写一个查询以显示部门名称和每个部门中的人员计数,如果人员不存在,则将计数显示为0。为人员计数命名为staff_count。根据部门名称对结果进行排序。
这就是我尝试过的。
select department_name,count(*) as staff_count
from left join staff on department.department_id=staff.staff_id
group by department_name order by department_name;
我认为我的代码中缺少一些内容。
答案 0 :(得分:0)
我将您的查询写为:
SELECT
d.department_name,
d.department_id,
COUNT(s.staff_id) AS cnt
FROM department d
LEFT JOIN staff s
ON d.department_id = s.department_id
GROUP BY
d.department_name,
d.department_id
ORDER BY
d.department_name;
您想从department
到staff
表中进行合并,以将每个部门记录乘以其包含的员工人数。我们计算员工价值,这可以处理给定部门没有员工的情况。
请注意,我假设department_id
是两个表中联接列的名称。如果不是,则相应地修改上面的查询。
答案 1 :(得分:0)
SELECT
d.department_name,
COUNT(s.staff_id) AS staff_count
FROM department d
LEFT JOIN staff s
ON d.department_id = s.department_id
GROUP BY
d.department_name,
d.department_id
ORDER BY
d.department_name;
答案 2 :(得分:0)
如果您想以其他方式执行此操作。然后,您可以尝试以下代码。
1 select d.department_name,count(s.staff_id) as staff_count
2 from department d,staff s
3 where d.department_id=s.department_id(+)
4 group by department_name
5 order by department_name;
答案 3 :(得分:0)
从部门中选择部门名称,人数(学生姓名)作为学生人数 自然加入学生 按部门名称分组 按部门名称排序;
答案 4 :(得分:-1)
select
department_name,
nvl(count(staff_id,0)as staff_count
from department
inner join staff
on department.department_id=staff.department_id
group by department_name
order by department_name