[英]Select all from one table and count from another and include nulls
I'm trying to get all ids from one table and a count of transactions from another table. 我正在尝试从一个表中获取所有ID,并从另一表中获取事务计数。 The trick is that an id may not be listed in the transaction table.
诀窍是,交易表中可能未列出ID。 In that case, I want the query to return 0 for that id.
在这种情况下,我希望查询为该ID返回0。 (I apologize for the bad formatting)
(对于格式错误,我深表歉意)
ID Table
ID
1
2
3
Trans Table
ID Trans
1 123
1 234
3 345
3 456
3 567
Query results
ID - Trans Count
1 2
2 0
3 3
I have this code, but it just isn't working for me and I can't figure out why. 我有这段代码,但是它对我不起作用,我不知道为什么。
SELECT A.ID, COUNT (B.TRANS) AS CNT
FROM A
LEFT JOIN B
ON A.ID = B.ID
WHERE B.DTE BETWEEN '01-Mar-2017' AND '31-Mar-2017' AND
A.CURRENT_FLAG = 1
GROUP BY A.ID
When using left join
, conditions on the first table go in the where
clause. 使用
left join
,第一个表上的条件将放在where
子句中。 Conditions on the second table go in the on
clause: 第二个表的条件放在
on
子句中:
SELECT A.ID, COUNT (B.TRANS) AS CNT
FROM A LEFT JOIN
B
ON A.ID = B.ID AND
B.DTE BETWEEN '01-Mar-2017' AND '31-Mar-2017' AND
WHERE A.CURRENT_FLAG = 1
GROUP BY A.ID;
I would check if the value is null if then just replace it with a 0 我会检查该值是否为null,然后将其替换为0
The NVL Function will work perfect for this scenario. NVL功能将在此情况下完美运行。
SELECT A.ID, COUNT (NVL(B.TRANS,0)) AS CNT
FROM A
LEFT JOIN B
ON A.ID = B.ID
WHERE B.DTE BETWEEN '01-Mar-2017' AND '31-Mar-2017' AND A.CURRENT_FLAG = 1
GROUP BY A.ID
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.