在T-SQL中使用SUM和ISNULL与WHERE子句

时间:2013-05-23 20:15:23

标签: sql-server tsql

我没有从下面的查询中获得预期的结果。我期待收回5,262条记录,而我只获得4,279条记录。我知道问题出在WHERE子句中。当我注释掉WHERE子句时,我得到了预期的记录数,但是数量不正确,因为我需要在Type字段上进行过滤。有什么建议吗?

SELECT
    a.Part,
    SUM(ISNULL(b.Qty,0)) AS Sales_Qty
FROM
    dbo.Parts a
    LEFT OUTER JOIN dbo.Sales b ON b.Part = a.Part
WHERE
    b.Type = 'O'
GROUP BY
    a.Part
ORDER BY
    a.Part

2 个答案:

答案 0 :(得分:6)

如果您在LEFT JOIN b (在这种情况下为WHERE)右侧的表格中的某个列上添加条件您将删除所有未满足条件的结果行,而不是将缺失值设置为NULL

相反,将其放在ON子句中;

SELECT
    a.Part,
    SUM(ISNULL(b.Qty,0)) AS Sales_Qty
FROM
    dbo.Parts a
    LEFT OUTER JOIN dbo.Sales b ON b.Part = a.Part AND b.Type = 'O'
GROUP BY
    a.Part
ORDER BY
    a.Part

答案 1 :(得分:3)

由于您已将过滤器放在WHERE子句中,因此基本上执行INNER JOIN,它只返回两个表中的匹配行,尝试将过滤器移动到JOIN:

SELECT a.Part,
   SUM(ISNULL(b.Qty,0)) AS Sales_Qty
FROM dbo.Parts a
LEFT OUTER JOIN dbo.Sales b 
   ON b.Part = a.Part
   AND b.Type = 'O'
GROUP BY a.Part
ORDER BY a.Part