我在Oracle 12c中有两个表,目标是计算table2中所有出现Flag NULL的事件,但是在table1中出现的Names旁边显示0
表1
ID,Name
001,Bob
009,Alice
015,Bob
019,Bob
026,Alice
500,Rob
505,Rob
表2
ID,Flag,Timestamp
001,NULL,02/04/2016 16:33:13,991000
010,NULL,02/04/2016 16:33:14,991000
023,NULL,02/04/2016 16:33:15,991000
019,True,02/04/2016 16:33:16,991000
026,True,02/04/2016 16:33:17,991000
500,NULL,02/04/2016 16:33:18,991000
505,NULL,02/04/2016 16:33:19,991000
我想
Name,COUNT
Alice,0
Bob,1
Rob,2
到目前为止,我的尝试是:
SELECT table1.Name, count(table1.Name) AS count
FROM table2
LEFT OUTER JOIN table1
ON table2.ID = table1.ID
WHERE table2.Flag IS null AND trunc(table2.Timestamp) = TRUNC(SYSDATE)
GROUP BY table1.Name
返回
Name,COUNT
Bob,1
Rob,2
答案 0 :(得分:2)
您需要将table1
的位置替换为table2
并计算table2的id
列(以便在不符合连接条件时排除空值)。
SELECT table1.Name, count(table2.id) AS count
FROM table1
LEFT OUTER JOIN table2
ON table2.ID = table1.ID
AND table2.Flag IS null
GROUP BY table1.Name
答案 1 :(得分:1)
请改为尝试:
SELECT table1.Name, count(table2.ID) AS count
FROM table1
LEFT OUTER JOIN table2 ON table2.ID = table1.ID
WHERE table2.Flag IS null
GROUP BY table1.Name