在Sum情况下的聚合函数

时间:2016-02-20 19:25:32

标签: sql-server

我正在尝试将我的then语句作为特定列的计数,但它无效。当我选择其他1 0时,它正在计算遭遇,我希望它能统计独特的患者,无论他们遇到多少次。

select 
sum (case when soc.tobacco_user_c in (1, 2, 4, 5) then 1 (**want to have this be
                                                            count(pat.pat_id - which is
                                                            varchar**)
                                                  else 0 end) Compliant
,sum(case when soc.tobacco_user_c in (1, 2, 3, 4, 5) then 1 else 0 end) TotalEligible,
dep.DEPARTMENT_NAME

from table 1 enc
inner join table2 soc on enc.PAT_ENC_CSN_ID = soc.PAT_ENC_CSN_ID 
inner join table3 ser2 on enc.pcp_prov_id = ser2.prov_id
inner join table4 dep on ser2.PRIMARY_DEPT_ID = dep.DEPARTMENT_ID
inner join patient table5 pat on enc.pat_id = pat.pat_id
where dep.department_id in ('100501201', '100502502', '100504501', '100607501', '100801804', '100801809', '200101101', 
'200201201', '200401401', '2013011301', '2016011601')
group by dep.DEPARTMENT_NAME

1 个答案:

答案 0 :(得分:0)

我认为您可以在要计算的字段上使用COUNT DISTINCT

COUNT(DISTINCT CASE WHEN soc.tobacco_user_c IN (1, 2, 4, 5) THEN pat.pat_id END) AS Compliant