SQL连接和来自不同表的计数

时间:2015-03-27 16:53:18

标签: sql

基本上我有两张桌子,一张是医生,第二张是预约,我想计算每位医生的预约,但也包括列表中没有任何约会的医生到目前为止我已经提出这个。

SELECT DISTINCT doctor.doctor_id
              , sum(case when appt_date > 0 then 1 else 0 end) AppointmentCount 
FROM appointment,doctor JOIN doctor d 
WHERE appointment.doctor_id = d.doctor_id 
group by doctor_id;

这会打印出每个医生的身份证,但是这样每个医生的计数都是完全一样的,而我希望他们根据已经预约的次数有不同的值。

知道如何解决这个问题吗?

4 个答案:

答案 0 :(得分:1)

删除distinct关键字(请注意您正在使用分组依据)。避免在where子句中使用Join;尝试使用on

Left Join会给你预期的结果。

您的查询将是:

SELECT d.doctor_id,
       sum(case when a.appt_date > 0 then 1 else 0 end) AppointmentCount 
FROM doctor d
left join appointment a  
on  d.doctor_id = a.doctor_id
group by d.doctor_id;

答案 1 :(得分:1)

Select d.doctor_id, count(a.app_date) as count
from doctor d left join appointment a on (d.doctor_id = a.doctor_id) 
group by d.doctor_id;

您可以在此处查看演示:SQLFiddle

答案 2 :(得分:0)

您不需要使用distinctGROUP BY已经对条目进行重复数据删除(因为它按doctor_id进行分组。

最简单的方法是使用left join

select d.doctor_id
     , count(a.appt_date) as appointmentCount
from doctor as d
     left join appointment as a on d.doctor_id = a.doctor_id
group by d.doctor_id

答案 3 :(得分:0)

select doctor.doctor_id, nvl(count(appointment),0)
from doctor, appointment
where doctor.doctor_id = appointment.doctor_id(+)
group by doctor.doctor_id

与doctor_id预约的外联接,由doctor_id分组。如果没有医生预约,请使用NVL,以便显示零