G
G
gelirgwenn2018-01-10 22:59:55
MySQL
gelirgwenn, 2018-01-10 22:59:55

How to calculate the number of doctors working per week?

Good day, there are two tables in MySQL:
The first is a list of doctors, structure (id, full_name, specialty, status), about 1000 records.
The second one is doctors' weekends (id, doctor_id, start_date, end_date), about 50 records-time intervals per doctor (about 50,000 records in total). start_date, end_date - unix timestamp format.
It is necessary to count the number of doctors who work, i.e. are not on vacation/day off for a given time interval, for example, a week.
If you need to find the number of surgeons for a given interval, for example, inputInterval with borders also in unix timestamp - everything is simple, a type request using a check for non-intersection of intervals in the condition works fine:

SELECT COUNT(doctors.id) AS total_doctors, doctors.speciality
FROM doctors
WHERE NOT EXISTS (
     SELECT holidays.id
     FROM holidays
     WHERE holidays.doctor_id = doctors.id
     AND holidays.start_date > inputInterval.end_date OR holidays.end_date < inputInterval.start_date
)
GROUP BY doctors.specialty
HAVING doctors.speciality = "хирург"

But, if not a single doctor is found, then several other time intervals should be suggested, when at least 1-2 surgeons work. Here I have a problem, tell me where to dig, who faced this.
I have a solution, but it seems to me - a curve.
1. Make a selection of all surgeons from the table of doctors
2. Select all weekends whose end_date is greater than today for surgeons
3. Form an array like doctor_id => list of weekend intervals
4. Merge all intervals in a loop so that from intervals like 01/02 - 01/03 and 01/02 - 01/04 we get one interval 01/02 - 01/04, i.e. merge intervals that are included in other intervals.
5. Then, in a loop, sort all intervals by start_date, and calculate free intervals, such as adding the end_date of the i-th record with the start_date of i+1 records.
6. Loop through all free intervals and calculate how many doctors do not converge with this interval, using the sample from point 2.
Maybe someone knows a different solution? I would be very grateful for your help! At least an idea, I will implement it myself

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
Boris Korobkov, 2018-01-10
@BorisKorobkov

view query using in condition check for non-intersection of intervals works fine

So it was badly tested. This query does not work for vacations that...
- start before the range and end after the range
- exactly match the range
- start or end inside the range

P
Pavel Belyaev, 2018-01-10
@PavelBelyaev

SELECT COUNT(doctors.id) AS total_doctors, doctors.speciality
JOIN holidays ON holidays.doctor_id = doctors.id AND (holidays.start_date > inputInterval.end_date OR holidays.end_date < inputInterval.start_date)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question