向当前查询添加第二个SUM

时间:2015-04-27 15:20:07

标签: sql sql-server

我正在尝试添加另一列以显示已拒绝的总计。我想添加一个Declined列,它将该SUM(D.FulfillmentAmt)作为Declined WHERE D.StatusID ='2'。目前我正在使用两个查询,但希望将它们合并为一个,使用下面的一个作为起点:

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

我当前的查询显示以下结果:

Approved | Budget | CommunityName
100      | 2000   | City1
250      | 3000   | City2
1330     | 5000   | City3
50       | 2000   | City4
0        | 3000   | City5
2500     | 7000   | City6

我希望它的功能如下:

Approved | Declined | Budget | CommunityName
100      | 100      | 2000   | City1
250      | 0        | 3000   | City2
1330     | 452      | 5000   | City3
50       | 863      | 2000   | City4
0        | 0        | 3000   | City5
2500     | 105      | 7000   | City6

我需要确保它仍然显示所有城市,无论他们是否在捐款表中有记录。例如,City5没有任何记录,但仍然显示为0.我希望保持这样。

1 个答案:

答案 0 :(得分:3)

您想使用条件聚合:

SELECT SUM(CASE WHEN status = '1' THEN D.FulfillmentAmt ELSE 0 END) as Approved,
       DB.Budget, DC.CommunityName,
       SUM(CASE WHEN status = '2' THEN D.FulfillmentAmt ELSE 0 END) as DeclinedAmount
. . .

然后在查询中使用D.StatusId IN ('1', '2')