Oracle SQL计数与日期要求

时间:2013-11-21 20:19:00

标签: sql oracle

我有2张表,如下所示。我需要向他在过去6个月内看到的病人和他见过的病人数列出医生的详细信息。

 - Patient

PatientNo | Name | Address | DrNo (FK) | Datevisit

 - Doctor

DrNo | Name | Contact

我的最终输出应该如下

DrNo | Name | Contact | PatientSeen

我的编码肯定是错误的,会感谢一些帮助,对sql来说是全新的。

select *, count(select * from patient where drno is not null) 
  from doctor, patient
where doctor.drno = patient.drno
  and trunc(patient.datevisit,'MM') >= trunc(add_months(sysdate,-6), 'MM')

3 个答案:

答案 0 :(得分:0)

试试这个:

SELECT DrNo,
       Name,
       Contact,
       (SELECT COUNT(*)
          FROM Patient
         WHERE Patient.DrNo = Doctor.DrNo
           AND MONTHS_BETWEEN(sysdate,Patient.datevisit) <= 6) as PatientSeen
  FROM Doctor

答案 1 :(得分:0)

select d.DrNo,d.Name,d.Contact,count(p.PatientNo)
from Doctor d left join Patient p on p.DrNo =d.DrNo
where MONTHS_BETWEEN(sysdate,p.Patient.datevisit) <= 6
group by d.DrNo,d.Name,d.Contact

答案 2 :(得分:0)

SELECT D.DrNo, D.Name, D.Contact, COUNT(P.PatientNo) AS PatientSeen
FROM DOCTOR D
LEFT JOIN PATIENT P ON D.DrNo = P.DrNo
WHERE P.Datevisit > ADD_MONTHS(sysdate, -6)
GROUP BY D.DrNo, D.Name, D.Contact