【问题标题】:How to count how many doctors are booked by each patient?如何计算每位患者预约了多少医生?
【发布时间】:2016-05-11 18:25:51
【问题描述】:

我需要结果看起来像:

PatientID   Doctors
Patient1    3
Patient2    2
Patient3    1

预定的桌子是这样的

GPS Table

PatientID   DoctorID  DATE
Patient1    Doctor1   2016-02-16
Patient1    Doctor1   2016-04-08
Patient1    Doctor2   2016-06-09
Patient2    Doctor3   2017-01-02
Patient2    Doctor6   2016-12-01
Patient3    Doctor1   2016-07-12

还有更多的预订,但我只是以这张桌子为例。 此外,我需要确保如果该人为医生预订了 2 次,则不会计算同一位医生。

我现在的代码是:

select Bookings.PatientID, count(Bookings.DoctorID) as Doctors from Bookings where Bookings.DoctorID;

感谢您的帮助!

【问题讨论】:

    标签: php mysql count


    【解决方案1】:

    在具有不同患者和医生的临时表上使用 Group by

     select Patient, count(*)
     from (
     select distinct Bookings.PatientID as Patient ,DoctorID as Doctors 
     from Bookings  ) as t
    
     Group by Patient;
    

    【讨论】:

    • Nice .. +1 .. 顺便说一句,我已经更新了我的问题,如果您有空闲时间,请查看it
    • @Shafizadeh 请解释你的新问题,看不到 cange d 在哪里......(但你不是 OP?..?)
    【解决方案2】:

    您正在寻找count(distinct):

    select b.PatientID, count(distinct b.DoctorID) as NumDoctors
    from Bookings b
    group by b.PatientID;
    

    【讨论】:

    • 区分和分组在同一列?
    【解决方案3】:

    试试这个:

    SELECT PatientID, count(DoctorID) FROM `GPS ` group by PatientID
    

    【讨论】:

      【解决方案4】:

      我这样做了,它奏效了:

      select PatientID as Patient, count(distinct(DoctorID)) as Doctors from Bookings, Patients group by PatientID;
      

      感谢您的帮助!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-09
        • 2020-04-05
        • 1970-01-01
        相关资源
        最近更新 更多