0

这是我到目前为止...

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]

以下是一些结果

姓名 count_yes count_no tot
姓名1 0 1 0
名称2 0 1 0
姓名3 0 273 273
姓名4 0 114 114

在大多数情况下它是正确的,我唯一需要的是如果 tot 为 0,则不要在 count_no 上求和。

有没有办法轻松做到这一点?

谢谢。

4

2 回答 2

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
于 2012-11-30T19:29:51.703 回答
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]
于 2012-11-30T19:28:47.437 回答