2016-02-10 43 views
0

我試圖顯示行,即使它們返回的計數爲零。然而沒有運氣。 我嘗試使用左連接。顯示具有零計數的行

select 
    a.Month, 
    count(b.InsuranceFromJob) [Number of Participants without Insurance] 
from 
    hsAdmin.ReportPeriodLkup a 
left join hsAdmin.ClientReport b on 
    b.ReportPeriod = a.ReportPeriodId 
where 
    b.insurancefromjob = 2 and 
    a.reportperiodid between (@lastReportId - 11) and @lastReportId 
group by 
    a.Month 
+0

嘗試次數使用'coalesce'或'zeroifnull'命令。請提及數據庫名稱。 – minatverma

+2

您在'WHERE'子句中對錶別名'b'有限制,所以您已經有效地將'LEFT OUTER JOIN'變成了'INNER JOIN'。 –

+2

嘗試將謂詞'b.insurancefromjob = 2'移動到'ON'子句 –

回答

1

由於CLIENTREPORT是在哪裏,只存在於CLIENTREPORT行會在結果集。

移動檢查的加盟,你會得到期望的結果:

select 
    a.Month, 
    count(b.InsuranceFromJob) [Number of Participants without Insurance] 
from 
    hsAdmin.ReportPeriodLkup a 
left join hsAdmin.ClientReport b on 
    b.ReportPeriod = a.ReportPeriodId 
and b.insurancefromjob = 2 
where 
    a.reportperiodid between (@lastReportId - 11) and @lastReportId 
group by 
    a.Month