我是SQL的新手,需要返回从2018年或更晚开始的每个办公室的员工人数。对于没有任何员工在01/01/2018之后开始的办公室,结果应为零。
Employees
---------------------------------
|id|office_id|name |start_date|
---------------------------------|
|1 | 1 | Kyle |2018-08-08|
|2 | 1 | Sarah |2017-02-28|
|3 | 3 | Moe |2019-01-01|
|4 | 3 | Adi |2018-11-04|
|5 | 3 | Kwun |2016-05-22|
---------------------------------
Offices
---------
|id|name |
---------|
|1 | CHI |
|2 | NYC |
|3 | LA |
---------
这将返回正确的计数,但是我需要它为办公室ID#2(NYC)返回零。我想念什么?
SELECT o.id, COUNT(e.id) AS NumberOfEmployees
FROM Offices AS o
LEFT JOIN Employees as e
ON office_id = o.id
WHERE start_date >= '2018-01-01'
GROUP BY o.id
答案 0 :(得分:3)
您必须将start_date >= '2018-01-01'
条件移到左联接中。这样,就可以看到没有员工的办公室:
SELECT o.id, COUNT(e.id) AS NumberOfEmployees
FROM Offices AS o
LEFT JOIN Employees as e
ON office_id = o.id
AND start_date >= '2018-01-01'
GROUP BY o.id