我有两个表,一个包含有关患者访问的信息:PatientName,DoctorName,DataOfVisit等,第二个表包含有关医生的信息:DoctorName和DoctorSpeciality。
我需要创建一个查询,向我打印PatientName,患者去过的医生数量以及不同专业的数量。
如果我跑
SELECT PatientName, COUNT(VISITS.DoctorName) as DocNum, Count(DoctorSpeciality) as SpecNum
FROM VISITS
INNER JOIN Doctors
ON VISITS.DoctorName = Doctors.DoctorName
GROUP BY PatientName, VISITS.DoctorName, DoctorSpeciality
我得到了医生的数量,但没有得到专业的数量,患者没有分组。
答案 0 :(得分:0)
在大多数数据库中,您只需使用count(distinct specialty)
。但是,Access并不支持这一点。
您可以使用两个group by
来执行您想要的操作:
SELECT PatientName, COUNT(*) as NumSpecialties, SUM(NumDocs) as NumDocs
FROM (SELECT PatientName, Doctors.DoctorSpeciality, COUNT(*) as NumDocs
FROM VISITS INNER JOIN
Doctors
ON VISITS.DoctorName = Doctors.DoctorName
GROUP BY PatientName, DoctorSpeciality
) as pd
GROUP BY PatientName;
答案 1 :(得分:0)
您可以在COUNT()函数中添加DISTINCT,也不应在GROUP BY中包含聚合字段。
以下是我将如何更改查询。
SELECT PatientName, COUNT(DISTINCT VISITS.DoctorName) as DocNum,
Count(DISTINCT DoctorSpeciality) as SpecNum
FROM VISITS INNER JOIN
Doctors ON VISITS.DoctorName = Doctors.DoctorName
GROUP BY PatientName
答案 2 :(得分:0)
将表名用于要从db
中选择的字段SELECT VISITS.PatientName,COUNT(VISITS.DoctorName)为DocNum,Count(Doctors.DoctorSpeciality)为SpecNum 来自参观 INNER JOIN医生 ON VISITS.DoctorName = Doctors.DoctorName GROUP BY PatientName,VISITS.DoctorName,DoctorSpeciality