MS SQL query to find next appointment available date (single nearest date) with remaining appointment greater than 0 for each department excluding cancelled appointments.
In my appointment table I have two sessions (Morning and evening) and departments include medicine, dermatology, dental and cardiology and also I have appointment setup table to store max appointment for each department for each session.
WITH AvailableAppointments AS (
SELECT a.department, a.session, MIN(a.appointment_date) AS next_available_date,
s.max_appointments - COUNT(a.appointment_date) AS remaining_appointments
FROM appointments a
JOIN appointment_setup s ON a.department = s.department AND a.session = s.session
WHERE a.appointment_date >= GETDATE() /* Consider appointments from today onwards */
AND a.department IN ('Medicine', 'Dermatology', 'Dental', 'Cardiology')
AND a.status != 'Cancelled' /* Exclude cancelled appointments */
GROUP BY a.department, a.session, s.max_appointments
HAVING s.max_appointments - COUNT(a.appointment_date) > 0 /* Remaining appointments greater than 0 */
)
SELECT department, session, MIN(next_available_date) AS nearest_appointment_date
FROM AvailableAppointments
GROUP BY department, session