在having语句中使用两个不同的度量

时间:2017-03-22 17:28:37

标签: mysql

我包含了我尝试使用的代码。我想要的是得到每个医生的遭遇id的数量。我想捕获至少有2次就诊或曾进行过一次预防性就诊的患者。我不知道如何使用having语句来完成这项工作。谢谢你的帮助。

SELECT  e.doctorID, COUNT(DISTINCT e.encounterID) AS VisitCount

FROM enc e

JOIN users u ON e.patientID = u.uid
Left JOIN diagnosis d ON e.encounterID = d.encounterID
LEFT JOIN items it ON d.itemID = it.itemID
LEFT JOIN itemdetail id ON it.itemID = id.itemID

WHERE e.encType = 1 AND e.status = 'CHK' AND e.deleteFlag = 0 AND 
e.date BETWEEN DATE_ADD((LAST_DAY(DATE_ADD(CURDATE(),INTERVAL -2 MONTH))), INTERVAL 1 DAY) AND LAST_DAY(DATE_ADD(CURDATE(),INTERVAL -1 MONTH)) 
    AND FLOOR(DATEDIFF(NOW(),u.ptdob)/365.25) >= 18 AND e.doctorID = e.resourceID 

        GROUP BY e.doctorID, id.value
        HAVING 
        COUNT(e.patientid)>=2 OR 
        id.value in ('Z00.00', 'Z00.01')

1 个答案:

答案 0 :(得分:0)

您不需要在grp by子句中包含id.value。尝试在带有id.value

的子句中给出有效条件
select e.doctorID,
COUNT(distinct e.encounterID) as VisitCount from enc e join users u on e.patientID = u.uid 
left join diagnosis d on e.encounterID = d.encounterID left join items it on 
d.itemID = it.itemID left join itemdetail id on 
it.itemID = id.itemID where e.encType = 1 and e.status ='CHK' and e.deleteFlag = 0 and
 e.date between DATE_ADD((LAST_DAY(DATE_ADD(CURDATE(), INTERVAL - 2 MONTH))), INTERVAL 1 DAY) 
and LAST_DAY(DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)) 
and 
FLOOR(DATEDIFF(NOW(), u.ptdob) / 365.25) >= 18 
and e.doctorID = e.resourceID group by e.doctorID
having COUNT(e.patientid) >= 2 
or sum(case when id.value in ('Z00.00','Z00.01') then 1
else 0 end)>=1