I have created a scheduling application for work and I have run into a problem which I've spent many days trying to figure out with no luck. The application pulls information from a database with a Patients table, Clinician table, and Appointments table.
Currently, when a user selects a Patient from a dropdown list in the application, a query is executed that returns all Clinicians which a user can pick to assign the Appointment to. The problem is that there are hundreds of Clinicians and Patients usually only see the same 3-4 Clinicians.
What I would like to do is create a query that pulls all Clinicians but displays those Clinicians who have had appointments with a specific Patient in the past FIRST and then lists every other Clinician afterwards.
Basically, the query needs to check the Appointments table for a specific PatientID, pull all the clinicians who have had appointments with this client in the past, and then under this list all clinicians who have not seen this patient.
Then best I have come up with looks like this but I don't really know what else to try at this point.
SELECT Clinician.att_id, Clinician.att_name,
Case When Clinician.att_id = Appointments.att_id THEN 1 ELSE 0 END as common
FROM Clinician inner join
Appointments
on Clinician.att_id = Appointments.att_id
order by common desc;
答案 0 :(得分:0)
If you want all clinicians, then you want a left join
or some other construct.
SELECT c.att_id, c.att_name
FROM Clinician
ORDER BY (CASE WHEN EXISTS (SELECT 1
FROM Appointments a
WHERE c.att_id = a.att_id AND
a.patient_id = @patient_id
)
THEN 1 ELSE 2
END)