2016-06-21 34 views
1

我只有數據直到四月本月。所以我想通過加入日曆表來使用LEFT JOIN將剩下的幾個月帶到年底。 。日曆表具有YearNumber,MonthNumber和MonthName。 我在做什麼錯?爲什麼LEFT JOIN不會給我帶NULL值的所有月份字段

SELECT  
      Underwriter, 
      sum(case when TransactionType IN ('Policy', 'Reinstatement') then 1 ELSE 0 END) as PoliciesBound,    
      b.MonthNum, 
      b.YearNum, 
      b.MonthName 

FROM  tblCalendar b 
LEFT JOIN Test_Plaza_ProductionReport a ON b.MonthNum=Month(a.EffectiveDate) AND b.YearNum = YEAR(a.EffectiveDate) 
--FROM  Test_Plaza_ProductionReport 
WHERE  Year(a.EffectiveDate)=2016 AND Underwriter <>'Batcheller, Jerry' 
GROUP BY Underwriter, 
      b.YearNum, 
      b.MonthName, 
      b.MonthNum 

結果應該是這樣的:enter image description here

但我的結果,卻直到4月: enter image description here

什麼我使用LEFT JOIN失蹤?

+2

你用'where'標準否定你的'outer join'。將該標準移至「join」,它應該適合您。 – sgeddes

+0

將標準移動到聯接?你什麼意思?謝謝 – Oleg

+0

提示:使用(更多)有意義的別名並將它們應用於所有列。目前還不清楚「承銷商」和「TransactionType」的來源。使用'...從tblCalendar作爲Cal將外部連接Test_Plaza_ProductionReport作爲ProdRpt ...'輸出。即使'C'和'PR'也會比'a'和'b'更有用。 – HABO

回答

2

正如我的評論所述,where標準是否定您的outer join。試試這個:

... 
FROM tblCalendar b 
    LEFT JOIN Test_Plaza_ProductionReport a ON  
     b.MonthNum=Month(a.EffectiveDate) AND 
     b.YearNum = YEAR(a.EffectiveDate) AND 
     a.Underwriter <>'Batcheller, Jerry' 
WHERE  b.YearNum=2016 
GROUP BY Underwriter, 
      b.YearNum, 
      b.MonthName, 
      b.MonthNum 

注意,我假設underwriter場報告表,而不是日曆表。

+0

太棒了。非常感謝你。對於簡單的問題抱歉。 – Oleg

相關問題