Skip to content
Advertisement

How to exclude weekends and holidays dates and find an expected date in MySQL?

I am working on a task where I have 2 tables. i.e, tickets and holidays.

Now I also have the number of days to complete the tickets. Now I need to find the expected date by excluding holidays(specified in the holidays table) and weekends.

Now I can able to find a date using ticket created date and days to complete the ticket. But unable to calculate the expected due date by removing holidays and weekends.

If ticket expected due date falls under holidays or weekends, we need to shift the expected due date ahead.

And after that we need to compare ticket_closed_date and expected_due_date.

If ticket_closed_date <= expected_due_date then need to return isSlaMet as YES. Else need to return isSlaMet as NO.

Tickets Table

enter image description here

Holidays Table

enter image description here

Example: Generally if a ticket is created on 2nd October,2020 and its days to complete is 3, then the expected due date would be, 5th October and we have a holiday, 5th October. But there are 1 holiday and 2 weekends in between ticket created date and expected due date. i.e, 3rd, 4th and 5th of October . So we need to extend the expected due date by 3 days(because 2 weekends + 1 Holiday). i.e, 8th October. Ticket is closed on 9th October.

Then we need to compare ticket closed date(9th october) and expected due date(8th October) and return isSlaMet as YES.

Expected Input

Expected Output

This is the query I have been using so far.

Advertisement

Answer

This is more complicated that it may seem. The simplest approach may be brute force: enumerate all days between the creation and closure date of the ticket with a recursive CTE (available in MySQL 8.0 only), then filter out the weekends and holidays to count the number of SLA days:

Demo on DB Fiddle:

tid | created_At          | apply_sla | ticket_closed_date  | days_to_complete | expected_due_date   | completed_in | is_sla_met
--: | :------------------ | :-------- | :------------------ | ---------------: | :------------------ | -----------: | ---------:
100 | 2020-10-02 00:00:00 | 1         | 2020-10-09 00:00:00 |                3 | 2020-10-08 00:00:00 |            4 |          0
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement