2015-04-14 241 views
0

如何在表B沒有記錄時從兩個表A和B合併和彙集數據。我只想爲表A中的所有記錄顯示零,表B中沒有與附加標準匹配的記錄。在這種情況下,我想返回模型值爲'cars'的物品總數。表B爲空時發生此問題。SQL Join返回空記錄

這裏是我的代碼片段:

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 

回答

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, 
+0

感謝。值現在顯示,但是(a.Year)顯示爲null。任何解決方案 – aby

+0

你在'A'年有'null'值嗎?如果是的話,你想怎麼做呢? –

+0

不,我已經在A中列出了年份值.A不能爲空 – aby

0

移動b.model =從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