我正在尝试将行汇总成类别。我有一个带有类别的表(r)和一个带有事务(v)的视图。为了得到结果,无论表v中是否有数据,我都需要所有类别。这是我的代码,当v中存在对应的数据时,它仅返回r表中的所有行。
SELECT SUM(ISNULL(v.PledgeAmount, 0)) AS Range1Pledge,
COUNT(DISTINCT v.CONSTITUENT_ID) AS Range1Count,
r.RangeTitle
FROM view_CASA_KPIDonorPyramidStep2 as v RIGHT OUTER JOIN
tbl_CASA_KPI_GiftRanges as r ON
v.RangeTitle = r.RangeTitle
WHERE (v.CAMPAIGN_ID = '2018') AND (v.PledgeDate < '2/1/2018')
GROUP BY r.RangeTitle
答案 0 :(得分:1)
WHERE
逻辑已移至LEFT JOIN
状态,以防止过滤没有事务的类别RIGHT
联接变成了LEFT
SQL:
SELECT r.RangeTitle,
SUM(ISNULL(v.PledgeAmount, 0)) AS Range1Pledge,
COUNT(DISTINCT v.CONSTITUENT_ID) AS Range1Count
FROM tbl_CASA_KPI_GiftRanges as r
LEFT OUTER JOIN view_CASA_KPIDonorPyramidStep2 as v
ON v.RangeTitle = r.RangeTitle
AND ( (v.CAMPAIGN_ID = '2018') AND (v.PledgeDate < '20180201') )
GROUP BY r.RangeTitle