I have the following query I am trying to run to determine how much available supply who have not been booked yet I have in an area on a particular day. I do this by generating a table of all workers by area and days available and using 'where' to ensure that they are 'not in' the confirmed booking table for that day.
I have two issues:
This is only able to give me my remaining available supply on 1 day. I would like to be able to show the remaining available supply for a series of days. Eg. remaining available supply for the next three days Day1, Day2 and Day3. This would mean that I have to compare my list of workers to a table of bookings for each day, iteratively. So col1 would count worker ids 'not in' Day1's booking table and the worker works on Day1s, col2 would count worker ids 'not in' Day2's booking table and the worker works on Day2s, ... etc.
This is a more minor issue. Given the code below, if the count of the available supply is 0, that area row is not in the resulting table. I have tried to use IFNULL on the count but that didn't work. I am therefore having to create a union between that and a query which lists all areas with 0 values and then choose each area with the max value. Is there a better way to do this?
The [daterange_start] fields are filtered fields substituted in by end user of dashboard.
select
area,
MAX(man_days_remaining)
from (
select doa.zip_code as area, count(w.user_ptr_id) as man_days_remaining
from domestic_worker w
left join domestic_worker_worker_operating_areas dwoa
on w.user_ptr_id = dwoa.worker_id
left join geography_operatingarea doa
on doa.id = dwoa.operatingarea_id
left join domestic_worker_days_available d
on w.user_ptr_id = d.worker_id
left join geography_city c
on c.id = w.worker_city_id
where w.user_ptr_id not in (
select w.user_ptr_id
from booking_booking b
left join domestic_jobcard j
on b.id = j.booking_id
left join domestic_worker w
on w.user_ptr_id = j.worker_id
where date(b.appointment_datetime) = date([daterange_start])
and b.booking_status = 'confirmed'
and w.user_ptr_id is not null)
and weekday([daterange_start]) + 1 = d.weekday_id
group by 1
UNION
select doa.zip_code as 'Area', '0', null
from geography_operatingarea doa
where doa.active = 1
) t
group by 1
order by 1 asc