How to count date difference excluding weekend and holidays in MySQL

后端 未结 5 1947
青春惊慌失措
青春惊慌失措 2020-12-01 12:35

I need to count days (business days) between two dates excluding weekend (most important) and holidays

SELECT DATEDIFF(end_date, start_date) from accounts
         


        
5条回答
  •  借酒劲吻你
    2020-12-01 13:17

    You might want to try this:

    1. Count the number of working days (took it from here)

      SELECT 5 * (DATEDIFF('2012-12-31', '2012-01-01') DIV 7) + MID('0123444401233334012222340111123400012345001234550', 7 * WEEKDAY('2012-01-01') + WEEKDAY('2012-12-31') + 1, 1)

      This gives you 261 working days for 2012.

    2. Now you need to know your holidays that are not on a weekend

      SELECT COUNT(*) FROM holidays WHERE DAYOFWEEK(holiday) < 6

      The result of this depends on your holiday table.

    3. We need to get that in one query:

      SELECT 5 * (DATEDIFF('2012-12-31', '2012-01-01') DIV 7) + MID('0123444401233334012222340111123400012345001234550', 7 * WEEKDAY('2012-01-01') + WEEKDAY('2012-12-31') + 1, 1) - (SELECT COUNT(*) FROM holidays WHERE DAYOFWEEK(holiday) < 6)

      This should be it.

    Edit: Please be aware that this only works properly if your end date is higher than your start date.

提交回复
热议问题