包括表1中的所有行和表1中的所有行

时间:2019-02-22 13:51:05

标签: sql-server

我正在尝试将行汇总成类别。我有一个带有类别的表(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

1 个答案:

答案 0 :(得分:1)

  • WHERE逻辑已移至LEFT JOIN状态,以防止过滤没有事务的类别
  • RIGHT联接变成了LEFT
  • 2/1/2018 替换为与语言环境无关的格式,假设它是 2018年2月1日

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