这是我到目前为止所拥有的......
SELECT pr.[name], SUM(COALESCE(qm.iscompleted,0)) count_yes,
SUM(COALESCE(qm.iscompleted,1)) count_no,
COUNT(p.id) AS tot
FROM (aco.practices pr
left JOIN aco.patients_practices ppr ON (ppr.practiceid = pr.id)
left JOIN aco.patients p ON (p.id = ppr.patientid)
LEFT JOIN aco.qmheader qm ON (qm.patientid = p.id AND qm.practiceid = pr.id)
)
WHERE (pr.parentaco = 30982)
GROUP BY pr.[name]
ORDER BY pr.[name]
以下是一些结果
name count_yes count_no tot name1 0 1 0 name2 0 1 0 name3 0 273 273 name4 0 114 114
在大多数情况下它是正确的,我唯一需要的是如果tot为0,则不在count_no上使用SUM。
有没有办法轻松做到这一点?
感谢。
答案 0 :(得分:2)
将您的select
条款更改为:
SELECT pr.[name],
SUM(COALESCE(qm.iscompleted,0)) AS count_yes,
(case when COUNT(p.id) > 0 then
SUM(COALESCE(qm.iscompleted,1))
else
0 end) AS count_no,
COUNT(p.id) AS tot
答案 1 :(得分:1)
使用HAVING
子句:
SELECT pr.[name], SUM(COALESCE(qm.iscompleted,0)) count_yes,
SUM(COALESCE(qm.iscompleted,1)) count_no,
COUNT(p.id) AS tot
FROM (aco.practices pr
left JOIN aco.patients_practices ppr ON (ppr.practiceid = pr.id)
left JOIN aco.patients p ON (p.id = ppr.patientid)
LEFT JOIN aco.qmheader qm ON (qm.patientid = p.id AND qm.practiceid = pr.id)
)
WHERE (pr.parentaco = 30982)
GROUP BY pr.[name]
HAVING COUNT(p.id) = 0
ORDER BY pr.[name]