我有这个问题,我似乎无法完美。任何帮助将不胜感激。使用SQL Server 2008 R2。
即使没有该社区的记录,我也会尝试显示结果中的所有社区。
SELECT COALESCE(SUM(D.FulfillmentAmt),0) as Approved, DB.Budget, DC.CommunityName
FROM Donations D
LEFT JOIN DCommunity DC ON D.Market = DC.CID
LEFT JOIN DBudget DB ON D.Market = DB.Community
WHERE D.StatusId = '1' AND DB.[Year] = year(getdate())
GROUP BY DC.CommunityName, DB.Budget
ORDER BY DC.CommunityName
目前显示以下结果:
Approved | Budget | CommunityName
10 | 2000 | City1
2400 | 3000 | City2
2358 | 5000 | City3
1855 | 2000 | City5
2200 | 3000 | City6
5600 | 7000 | City8
正如您所看到的那样,它缺少City4和City7,因为dbo.Donations表中没有针对这些城市的记录。即使他们没有记录,我仍然希望这两个人显示批准金额为0。
答案 0 :(得分:4)
由于你想要所有社区,作为一种风格,我总是把它作为我加入的第一张桌子(我更容易思考)。然后,您需要将WHERE条件适当地移动到JOIN子句中,因为将它们保留在WHERE中会强制它像INNER JOIN一样运行。此外,DBudget上的连接需要更新以返回DCommunity表。
SELECT COALESCE(SUM(D.FulfillmentAmt),0) as Approved, DB.Budget, DC.CommunityName
FROM DCommunity DC
LEFT JOIN DBudget DB ON DC.CID = DB.Community AND DB.[Year] = year(getdate())
LEFT JOIN Donations D ON D.Market = DC.CID AND D.StatusId = '1'
GROUP BY DC.CommunityName, DB.Budget
ORDER BY DC.CommunityName
答案 1 :(得分:4)
然后使用left join
启动DCommunity
,如果这是您要保留的内容。此外,您需要将一些条件移至on
子句,因此left join
不会成为inner
加入次数:
SELECT COALESCE(SUM(D.FulfillmentAmt), 0) as Approved, DB.Budget, DC.CommunityName
FROM DCommunity DC LEFT JOIN
Donations D
ON D.Market = DC.CID LEFT JOIN
DBudget DB
ON D.Market = DB.Community AND
D.StatusId = '1' AND
DB.[Year] = year(getdate())
GROUP BY DC.CommunityName, DB.Budget
ORDER BY DC.CommunityName;
答案 2 :(得分:2)
将条件从WHERE
移至ON
,以获得真实的LEFT JOIN
。 (否则你会得到一个常规的INNER JOIN ...)
SELECT COALESCE(SUM(D.FulfillmentAmt),0) as Approved,
DB.Budget,
DC.CommunityName
FROM DCommunity DC
LEFT JOIN Donations D ON D.Market = DC.CID AND D.StatusId = '1'
LEFT JOIN DBudget DB ON D.Market = DB.Community AND DB.[Year] = year(getdate())
GROUP BY DC.CommunityName, DB.Budget
ORDER BY DC.CommunityName