此问题在此处已有答案:
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
字符串
1条答案
按热度按时间zpf6vheq1#
使用
left outer join
,而不是inner join
。并计算e.eployee_id
。字符串
看看这个sqlFiddle。这可能与您的原始查询尽可能接近,并且仍然得到相同的答案。你也可以把它写成
型
或者是
型
尽管这两个都可能与您的原始查询相距较远。