I have a calendar in a table and I should take out the equipment availability per month until today's date. The table is as follows:
create table period
(GCP_START date, GCP_END date,
GCP_MONSTART int, GCP_MONEND int,
GCP_TUESSTART int, GCP_TUESEND int,
GCP_WEDSTART int, GCP_WEDEND int,
GCP_THURSSTART int, GCP_THURSEND int,
GCP_FRISTART int, GCP_FRIEND int,
GCP_SATSTART int, GCP_SATEND int,
GCP_SUNSTART int, GCP_SUNEND int);
insert into period values
('2020-10-25', '2020-10-31', 360, 1320, 360, 1320, 360, 1320, 360, 1320, 360, 1320, NULL, NULL, NULL, NULL),
('2020-11-01', '2020-11-30', 360, 1320, 360, 1320, 360, 1320, 360, 1320, 360, 1320, NULL, NULL, NULL, NULL),
('2020-12-01', '2020-12-23', 360, 1320, 360, 1320, 360, 1320, 360, 1320, 360, 1320, NULL, NULL, NULL, NULL),
('2020-12-24', '2020-12-24', 360, 720, 360, 720, 360, 720, 360, 720, 360, 720, NULL, NULL, NULL, NULL),
('2020-12-27', '2020-12-31', 480, 1020, 480, 1020, 480, 1020, 480, 1020, 480, 1020, NULL, NULL, 360, 720);
Every numeric value corresponds to a start or end in minutes (i.e. 360 -> 6:00 AM, 1320 -> 10:00 PM; the difference between 1320 and 360 is 960 minutes and is the effective availability of equipment on the day in example). Every record in the "period" table doesn't cross 2 or more months: is only a portion of 1 month. Given the above dataset, I'd like to get the following results:
(Period, minutes_of availability)
('2020-10', 4800), <---- 1 Monday = 960 minutes + 1 Tuesday = 960 minuntes + 1 Wednesday = 960 minutes .....
('2020-11', 20160), <---- 5 Monday = 4800 minutes + 4 Tuesday = 3840 minutes + 4 Wednesday = 3840 minutes .....
('2020-12', 17220), <---- 3 Monday (until 23 December and before today) = 2880 minutes + 4 (until 23 December and before today) ..... 24 December ha a different availability, after 27 too
Moreover the calculation should stop with the "current day" so I don't want to calculate for the whole calendar. Can someone help me to solve this problem? My database engine is SQL Server.
Over