SQL Join返回空记录

时间:2015-04-14 14:33:26

标签: sql database sql-server-2008 join

当表B上没有记录时,如何从两个表A和B中加入和汇总聚合数据。我只想为表A中的所有记录显示零,表B中没有匹配的记录和其他标准。在这种情况下,我想返回模型值为“cars”的项目总数。当表B为空时会发生此问题。

这是我的代码段:

SELECT 10 as No,'Total' as Label, 
                SUM(CASE WHEN (a.year = b.year) THEN 1 ELSE 0 END) AS Value,
                (a.Year) as Year
FROM A a LEFT JOIN B b ON a.year = b.year
WHERE (isDeleted = 0 OR isdeleted is null) and b.model='cars'
GROUP BY a.year
order by YearMonth asc

2 个答案:

答案 0 :(得分:1)

问题在于:

WHERE (isDeleted = 0 OR isdeleted is null) and b.model='cars'

如果b为空,则b.model将为null,而您的where子句将填写这些记录。您应该将该条件移至JOIN子句:

FROM A a LEFT JOIN B b ON a.year = b.year and b.model='cars'
WHERE (isDeleted = 0 OR isdeleted is null)

请注意,您的SUM可能只是COUNT,因为不计算空值:

COUNT(b.year) AS Value,

答案 1 :(得分:0)

将b.model ='cars'从WHERE子句移动到ON子句(否则执行常规内连接。)

SELECT 10 as No,
       'Total' as Label, 
       SUM(CASE WHEN (a.year = b.year) THEN 1 ELSE 0 END) AS Value,
       (a.Year) as Year
FROM A a LEFT JOIN B b ON a.year = b.year and b.model='cars'
WHERE (isDeleted = 0 OR isdeleted is null) 
GROUP BY a.year
order by YearMonth asc