获得具有条件的独特计数

时间:2016-06-22 17:01:31

标签: sql tsql reporting-services

我怎样才能简单地计算不同ControlNo的COUNT,只有TYPE列=' New Business'。但我需要在将要加入日历表的查询中执行此操作。

SELECT      underwriter,
            --ControlNo,
            SUM(CASE WHEN Type = 'New Business' AND RevisedStatus IN ('Bound','Cancelled','Notice of Cancellation') THEN 1 ELSE 0 END ) as  'Binds - NEW BUSINESS',
            SUM(CASE WHEN Type = 'Renewal'      AND RevisedStatus IN ('Bound','Cancelled','Notice of Cancellation') THEN 1 ELSE 0 END ) as  'Binds - RENEWALS',
            SUM(CASE WHEN Type = 'Rewrite'      AND RevisedStatus IN ('Bound','Cancelled','Notice of Cancellation') THEN 1 ELSE 0 END ) as  'Binds - REWRITE',


            SUM(CASE WHEN Type = 'New Business'  THEN 1 ELSE 0 END ) as  Submissions1,
            count(  case when type = 'New Business' then ControlNo  else 0 end) as Submissions2,


            b.MonthNum,
                b.YearNum,
                b.MonthName

FROM        tblCalendar b  
LEFT JOIN   Test_Plaza_ClearanceReport a ON b.MonthNum=Month(a.EffectiveDate)    
            AND b.YearNum = YEAR(a.EffectiveDate)
            AND a.Underwriter ='Brown, Debra'
WHERE       b.YearNum = 2016
GROUP BY
                b.MonthName,
                b.MonthNum,
                b.YearNum,
                --ControlNo,
                underwriter

我的结果略有不同。我应该相信哪一个? enter image description here

1 个答案:

答案 0 :(得分:1)

您可以将其表达为:

  count(distinct  case when type = 'New Business' then ControlNo  end) as UniqueValues

注意:没有else;没有它,表达式的计算结果为NULL,并且不计算值。