从一个表中选择all并从另一个表中计数并包含空值

时间:2017-03-15 00:51:17

标签: sql

我正在尝试从一个表中获取所有ID,并从另一个表中获取事务计数。诀窍是可能没有在事务表中列出id。在这种情况下,我希望查询为该id返回0。 (我为糟糕的格式道歉)

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

我有这个代码,但它对我不起作用,我无法弄清楚原因。

  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

2 个答案:

答案 0 :(得分:2)

使用left join时,第一个表中的条件会进入where子句。第二个表的条件在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;

答案 1 :(得分:0)

如果只是用0

替换它,我会检查该值是否为null

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