[英]How to count occurrences across two tables in Oracle?
I have two tables in Oracle 12c, goal is to count all occurrences in table2 which have Flag NULL, but also display 0 next to Names which are present in table1 我在Oracle 12c中有两个表,目标是对table2中具有Flag NULL的所有事件进行计数,但在table1中存在的名称旁边也显示0
table1 表格1
ID,Name
001,Bob
009,Alice
015,Bob
019,Bob
026,Alice
500,Rob
505,Rob
table2 表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
I'd like to get 我想得到
Name,COUNT
Alice,0
Bob,1
Rob,2
My attempt so far is: 到目前为止,我的尝试是:
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
Returning 返回
Name,COUNT
Bob,1
Rob,2
You need to replace the position of table1
with table2
and count the id
column of table2 (to exclude null values when the join condition is not met) . 您需要将
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
Try this instead: 尝试以下方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.