使用SQL计数(*)和分组依据显示包括零

时间:2014-05-16 06:04:05

标签: sql

对于此查询,我想使用SQL Count(*)显示零记录,下面的group by是我的SQL查询:

SELECT  B.BranchName as Filter,
Coalesce(COUNT(*), '0')   AS NoofSplits,
SUM(ls.Amount) AS TotalLoanValue
FROM    dbo.tblBranch B                     
LEFT OUTER JOIN dbo.tblLoan L ON L.BranchID = B.BranchID
LEFT OUTER JOIN dbo.tblLoanSplit LS ON L.LoanID = LS.LoanID
WHERE  LS.DateSettlement BETWEEN @StartDate AND @EndDate
GROUP BY B.BranchName
ORDER BY B.BranchName

1 个答案:

答案 0 :(得分:0)

执行外部联接时不要使用COUNT(*),如果没有要加入的行,则返回1 svn。在您的情况下,您必须COUNT外表的连接列:

SELECT  B.BranchName as Filter,
    COUNT(LS.LoanID)   AS NoofSplits,
SUM(ls.Amount) AS TotalLoanValue
FROM    dbo.tblBranch B                     
LEFT OUTER JOIN dbo.tblLoan L ON L.BranchID = B.BranchID
LEFT OUTER JOIN dbo.tblLoanSplit LS ON L.LoanID = LS.LoanID
WHERE  LS.DateSettlement BETWEEN @StartDate AND @EndDate
GROUP BY B.BranchName
ORDER BY B.BranchName