0

有两个表 tbldoctor 和 tblschedule

医生

 doc_id(PK)    docMrId        docfname
      1          22             manish
      2          23             rahul
      3          22             ashish
      4          24             ahemad
      5          22             narendra
      6          22             akshat

tblschedule

  doctor_id(FK)    mr_id       schedule_date
     1              22          2012-06-12
     1              22          2012-06-13
     3              22          2012-06-14
     3              22          2012-06-14
     4              24          2012-06-12
     4              24          2012-06-12
     5              22          2012-06-14
     5              22          2012-06-15
     5              22          2012-06-12

我想要的是所有医生的列表和在 tblschedule 表中重复的特定医生的计数,其中提供了 schedule_date 参数和 mr_id 我们假设 mr_id =22 和 schedule_date 在 2012-06-01 到 2012-06-31 之间

输出应该看起来像

  doc_id         docfname      count
    1               manish       2
    3               rahul        2
    5               narendra     3
    6               akshat       0
4

4 回答 4

2
select d.doc_id, docfname, count(mr_id) as count
from tbldoctor d
left outer join tblschedule s on s.doctor_id = d.doc_id
where mr_id = 22 
and schedule_date between '2012-06-01' and '2012-06-31'
group by s.doctor_id

编辑

select d.doc_id, 
       docfname, 
       sum(case when mr_id = 22 
                then 1 
                else 0 
           end) as count
from tbldoctor d
left outer join tblschedule s on s.doctor_id = d.doc_id
and schedule_date between '2012-06-01' and '2012-06-31'
group by s.doctor_id

SQLFiddle 示例

编辑 2

怎么样

select d.doc_id, docfname, count(mr_id) as count
from tbldoctor d
left outer join tblschedule s on s.doctor_id = d.doc_id and mr_id = docmrid
where docmrid = 22 
and (schedule_date between '2012-06-01' and '2012-06-31' or mr_id is null)
group by s.doctor_id
order by d.doc_id

SQLFiddle 示例

于 2012-06-27T05:14:55.737 回答
1

不是 100% 确定我理解你的意思,但这会给你一个所有医生 ID 的列表,以及两个给定日期之间每个医生 ID 的计划项目数。

SELECT tbldoctor.doc_id, COUNT(*) cnt
FROM tbldoctor d INNER JOIN tblschedule s
    ON d.doc_id = s.doctor_id
WHERE s.schedule_date BETWEEN '2012-06-12' AND '2012-06-15'
GROUP BY tbldoctor.doc_id
于 2012-06-27T05:14:57.867 回答
0
SELECT * FROM `tbldoctor` JOIN `tblschedule` ON `tblschedule`.doctor_id(FK) = `tbldoctor`.doc_id(PK)
于 2012-06-27T05:16:10.073 回答
0
SELECT tbldoctor.doc_id, COUNT(*) cnt FROM tbldoctor d INNER JOIN tblschedule s     ON d.doc_id = s.doctor_id WHERE s.schedule_date BETWEEN '2012-06-12' AND '2012-06-15' GROUP BY tbldoctor.doc_id
于 2012-06-27T05:45:17.753 回答