在SQL中计算唯一值

时间:2017-12-11 19:47:03

标签: sql-server

我遇到了SQL问题。 我有两张桌子:个人和病人治疗。 个人表具有个人信息,治疗表具有接受治疗的个人ID和患者ID。 我需要找到给不同患者提供最多治疗的个人。 我尝试过以下方法:

   SELECT ID , First_Name , Last_Name
   FROM Personal JOIN Patients_Treatments ON ID = Personal_id 
   GROUP BY ID , First_Name , Last_Name
   HAVING COUNT(*) >= ALL (SELECT COUNT(Personal_id) FROM Patients_Treatments 
   GROUP BY Personal_id)

问题在于它给予了给予最多治疗的个人,而不是给予不同患者最多治疗的人。 谢谢你的时间!

编辑: 如果有兴趣的话,找到解决方案:

SELECT Personal.ID,First_Name,Last_Name
FROM Personal,Patients_Treatments
WHERE Personal.id = Patients_Treatments.Personal_id
GROUP BY Personal.ID,First_Name,Last_Name
HAVING COUNT(distinct Patient_ID) >= all(SELECT COUNT(distinct Patient_ID) 
FROM [Patients_Treatments] GROUP BY Personal_id)

1 个答案:

答案 0 :(得分:2)

这将返回最高待遇的个人。

SELECT TOP 1 WITH TIES ID , First_Name , Last_Name
FROM Personal JOIN Patients_Treatments ON ID = Personal_id 
GROUP BY ID , First_Name , Last_Name
ORDER BY COUNT(DISTINCT Patient_ID) DESC