oracle 各部门员工人数[重复]

kkih6yb8  于 2023-08-03  发布在  Oracle
关注(0)|答案(1)|浏览(113)

此问题在此处已有答案

Row that should have a 0 count not showing(3个答案)
17天前关闭
我正在查每个部门的员工人数。我有下面的设置和代码,几乎可以工作。
正如你所看到的,我有4个部门,但其中只有3个(1,2,4)有员工。我怎样才能在我的输出中得到部门3,它显示0个员工。

CREATE TABLE departments(  department_id, department_name) AS
SELECT 1, 'IT' FROM DUAL UNION ALL
SELECT 2, 'Sales' FROM DUAL UNION ALL
SELECT 3, 'Marketing' FROM DUAL UNION ALL
SELECT 4, 'Finance' FROM DUAL;

CREATE TABLE employees (employee_id, first_name, last_name, hire_date, salary,  department_id) AS
SELECT 1, 'Lisa', 'Saladino', DATE '2001-04-03', 160000, 1 FROM DUAL UNION ALL
SELECT 2, 'Sandy', 'Herring', DATE '2011-08-04', 150200, 1 FROM DUAL UNION ALL
SELECT 3, 'Beth', 'Cooper', DATE '2019-03-05', 60700, 1 FROM DUAL UNION ALL
SELECT 4, 'Carol', 'Orr', DATE '2007-11-11', 70125,1 FROM DUAL UNION ALL
SELECT 5, 'Vicky', 'Palazzo', DATE '2004-09-17', 68525,2 FROM DUAL UNION ALL
SELECT 6, 'Cheryl', 'Ford', DATE '2020-05-10', 110000,1 FROM DUAL UNION ALL
SELECT 7, 'Leslee', 'Altman', DATE '2008-12-10', 66666, 1 FROM DUAL UNION ALL
SELECT 8, 'Jill', 'Coralnick', DATE '2001-04-11', 190000, 2 FROM DUAL UNION ALL
SELECT 9, 'Faith', 'Aaron', DATE '2001-04-17', 122000,2 FROM DUAL UNION ALL
SELECT 10, 'Silvio', 'Dante', DATE '2022-10-16', 102150,4 FROM DUAL UNION ALL
SELECT 11, 'Jerry', 'Torchiano', DATE '2022-10-30', 112660,4 FROM DUAL;

select 
  d.department_id,
  d.department_name, 
 count(*) as cnt
 from departments d
 INNER join employees e  on e.department_id = d.department_id 
 group by
   d.department_id,
   d.department_name
ORDER BY d.department_id;

Department_Id Department_name CNT
1   IT       6
2   Sales    3
4   Finance  2

字符串

zpf6vheq

zpf6vheq1#

使用left outer join,而不是inner join。并计算e.eployee_id

select 
  d.department_id,
  d.department_name, 
 count(e.employee_id) as cnt
 from departments d
 left outer join employees e  on e.department_id = d.department_id 
 group by
   d.department_id,
   d.department_name
ORDER BY d.department_id;

字符串
看看这个sqlFiddle。这可能与您的原始查询尽可能接近,并且仍然得到相同的答案。你也可以把它写成

select 
  d.department_id,
  d.department_name, 
  (select count(*)
     from employees e 
    where e.department_id = d.department_id) as cnt
 from departments d
 group by
   d.department_id,
   d.department_name
ORDER BY d.department_id;


或者是

select 
  d.department_id,
  d.department_name, 
  nvl( e.cnt, 0) as cnt
 from departments d
 left outer join (select e.department_id, count(*) cnt
                    from employees e
                   group by e.department_id) e
              on d.department_id = e.department_id
ORDER BY d.department_id;


尽管这两个都可能与您的原始查询相距较远。

相关问题