SQL - 查询不存在的记录为NULL

时间:2017-01-05 10:41:59

标签: sql-server

我希望记录能够毫无疑问地进入。 请帮我。谢谢你。

SELECT 
    ROUTE_ID,
    ISNULL(COUNT(*), 0) AS TOTAL_CALL
FROM 
    dbo.tblCall_Report AR 
CROSS JOIN 
    tblRoute R 
INNER JOIN 
    tblNotification_Report BR ON R.ROUTE_ID = BR.RouteID
WHERE 
    CAST(BR.NotificationDateTime AS DATE) = '04.01.2017'
    AND BR.CallNotification = 1 
    AND (BR.NotificationStatus = 1 OR BR.NotificationStatus IS NULL)
    AND BR.RouteID IN (7434,7423)
GROUP BY 
    ROUTE_ID

tblCall_Report

NotificationDateTime
----------------------
2017-04-01

tblNotification_Report

NotificationDateTime     RouteID
--------------------------------
2017-04-01                 7434

结果:

ROUTE_ID  | TOTAL_CALL
----------+-----------
   7434   |      1

我想要这些结果:

ROUTE_ID | TOTAL_CALL
---------+-----------
   7434  |    1    
   7423  |    0

3 个答案:

答案 0 :(得分:0)

如果原始表中存在路由7423,那么我的猜测是INNER JOIN正在过滤此路由。改为使用LEFT JOIN

SELECT ROUTE_ID,
       ISNULL(COUNT(*),0) AS TOTAL_CALL
FROM dbo.tblCall_Report AR
CROSS JOIN tblRoute R
LEFT JOIN tblNotification_Report BR
    ON R.ROUTE_ID = BR.RouteID AND
       BR.RouteID IN (7434, 7423)
WHERE CAST(BR.NotificationDateTime AS DATE) = '04.01.2017' AND
      BR.CallNotification = 1 AND
      (BR.NotificationStatus =1 OR BR.NotificationStatus IS NULL)
GROUP BY ROUTE_ID

答案 1 :(得分:0)

您应该使用LEFT OUTER JOIN,并且需要相应地修改WHERE子句。检查以下查询 选择     ROUTE_ID,     SUM(如果BR.RouteID不为1,则为0结束时的情况)为TOTAL_CALL 从     dbo.tblCall_Report AR 交叉加入     tblRoute R. LEFT JOIN     tblNotification_Report BR ON R.ROUTE_ID = BR.RouteID     AND CAST(BR.NotificationDateTime AS DATE)=' 04.01.2017'     AND BR.CallNotification = 1     AND(BR.NotificationStatus = 1或BR.NotificationStatus IS NULL) 在哪里R.Route_ID IN(7434,7423) 通过...分组     ROUTE_ID 以下是我得到的结果。 希望这能帮到你。

答案 2 :(得分:0)

你需要:

  • 使用left join
  • 使用您的可空值将操作数移动到on
  • 使用R在哪里,因为它肯定有价值 SELECT ROUTE_ID, CASE ISNULL(MIN(BR.RouteID), 0) WHEN 0 THEN 0 ELSE COUNT(*) END AS TOTAL_CALL FROM dbo.tblCall_Report AR CROSS JOIN tblRoute R LEFT JOIN tblNotification_Report BR ON R.ROUTE_ID = BR.RouteID AND CAST(BR.NotificationDateTime AS DATE) = '04.01.2017' AND BR.CallNotification = 1 AND (BR.NotificationStatus = 1 OR BR.NotificationStatus IS NULL) GROUP BY WHERE R.RouteID IN (7434,7423) ROUTE_ID