我有两张桌子,一张叫医生,一张叫约会。他们都有共同关系的医生ID。我需要能够生成医生 ID 列表以及为每个有零个或多个预约的医生进行的预约数量。(表内容见图片)
使用下面的代码,我可以获得医生列表) id 以及预约次数,但它不会显示医生列表中的零预约医生。我需要做什么修改?
SELECT doctor_id, COUNT(DISTINCT appt_time) AS No_APP FROM appointment GROUP BY doctor_id;
这就是我从中得到的
尝试:
SELECT doctor.doctor_id, COUNT(appointment.appt_time) AS No_APP
FROM doctor
LEFT JOIN appointment
ON appointment.doctor_id = doctor.doctor_id
GROUP BY doctor.doctor_id;
使用左连接:
SELECT doctor.doctor_id, COUNT(appt_time) AS No_APP FROM doctor LEFT JOIN appointment ON doctor.doctor_id = appointment.doctor_id GROUP BY doctor.doctor_id;
它应该可以解决问题
这应该有效:
select
d.doctor_id
,count(distinct a.appt_time) as No_APP
from doctor d
left join appointment a on d.doctor_id=a.doctor_id
group by d.doctor_id
使用左连接:
SELECT doctor.doctor_id, COUNT(DISTINCT appt_date, appt_time) AS No_APP
FROM doctor
LEFT JOIN appointment
ON doctor.doctor_id = appointment.doctor_id
GROUP BY doctor_id;