2017-07-07 60 views
1

我有這兩個表:如何包括查詢零計數結果

運營商:

Id Nome 
--+---- 
1 JDOE 
2 RROE 
3 MMOE 

電話:

Id CallDate OpId 
--+--------+---- 
1 20161228 2 
2 20161228 3 
3 20161228 2 
4 20161228 3 
5 20170104 1 
6 20170104 2 
7 20170104 1  

而這個查詢:

SELECT Operators.id, Operators.Nome, Count(Calls.OpId) AS CountCalls 
FROM Operators LEFT JOIN Calls ON Operators.id = Calls.OpId 
GROUP BY Calls.CallDate, Operators.id, Operators.Nome 
HAVING Calls.CallDate=20170104; 

其中返回:

Id Nome CountCalls 
--+----+---------- 
1 JDOE   2 
2 RROE   1 

我該如何讓它返回呢?

Id Nome CountCalls 
--+----+---------- 
1 JDOE   2 
2 RROE   1 
3 MMOE   0 

即,如何在任何查詢包括也由具有在左接合表中沒有發生,至少在由查詢過濾標準中定義的數據切片主表中的結果爲零?

PS。這是訪問2013

PS2。我讀過this answer,但看不出與我所做的有什麼不同,所以如果有人能在幫我複製我之前幫助我(也可能有相同的疑問),我將非常感激。

非常感謝!

+0

不要引用任何LEFT在WHERE子句謂詞不允許空值加入表列。 – Serg

回答

4

因爲您在HAVING子句中提及Calls.CallDate,所以您將刪除沒有呼叫的運營商。如果沒有呼叫,則CallDate將是NULL,並且NULL=20170104不是真的,因此這些行被排除。你需要這個謂詞移動到連接語句:

SELECT Operators.id, Operators.Nome, Count(Calls.OpId) AS CountCalls 
FROM Operators LEFT JOIN Calls ON (Operators.id = Calls.OpId AND Calls.CallDate=20170104) 
GROUP BY Calls.CallDate, Operators.id, Operators.Nome; 

你也不必按Calls.CallDate,因爲你只有一個,所以你可以只使用:

SELECT Operators.id, Operators.Nome, Count(Calls.OpId) AS CountCalls 
FROM Operators LEFT JOIN Calls ON (Operators.id = Calls.OpId AND Calls.CallDate=20170104) 
GROUP BY Operators.id, Operators.Nome; 

由於一邊HAVING是錯誤的運算符。 HAVING是用於過濾聚集,因爲你沒有過濾的集合,你只需要使用WHERE

SELECT Operators.id, Operators.Nome, Count(Calls.OpId) AS CountCalls 
FROM Operators LEFT JOIN Calls ON Operators.id = Calls.OpId 
WHERE Calls.CallDate=20170104 
GROUP BY Calls.CallDate, Operators.id, Operators.Nome; 

你會使用HAVING如果你想郝曉紅上CountCalls,例如,如果你只是想操作符取得了超過1叫你可以使用:

SELECT Operators.id, Operators.Nome, Count(Calls.OpId) AS CountCalls 
FROM Operators LEFT JOIN Calls ON Operators.id = Calls.OpId 
WHERE Calls.CallDate=20170104 
GROUP BY Calls.CallDate, Operators.id, Operators.Nome 
HAVING Count(Calls.OpId) > 1; 

這隻會返回下面q

Id Nome CountCalls 
--+----+---------- 
1 JDOE   2 
+0

只是一個觀察:因爲這些更改已完成,MS-Access將拒絕在設計模式下顯示此查詢,它將只能用作SQL或結果視圖。顯然,它的接口不能處理這個更復雜的Join子句。在MS上對此感到羞恥... – VBobCat

+0

好吧,對於任何非典型連接都是如此,我也不會因此而羞恥MS。它們無法在設計視圖中正確表示,並且在查詢中不應該隱藏元素,這些元素在那裏沒有表示。 –

1

嘗試uery:

SELECT o.id, o.name, count(c.opid) as countcalls 
FROM Operators o LEFT JOIN calls c ON o.id = c.opid AND c.calldate=20170104 
GROUP BY c.calldate, o.id, o.name 
ORDER BY o.id; 

輸出:

+------+------+------------+ 
| id | name | countcalls | 
+------+------+------------+ 
| 1 | JDOE |   2 | 
| 2 | RROE |   1 | 
| 3 | MMOE |   0 | 
+------+------+------------+