数据库
首页 > 数据库> > SQL实现2个日期之间的工作日数(MySQL)(转)

SQL实现2个日期之间的工作日数(MySQL)(转)

作者:互联网

限制条件:只能计算同一年的工作日,如果您需要跨年计算,请输入2次即可。

DROP FUNCTION IF EXISTS `workdaynum`;
DELIMITER $$
CREATE FUNCTION `workdaynum`(`datefrom` date,`dateto` date) 
RETURNS int(20) NO SQL
BEGIN
    declare days int default 1;
    if (datefrom > dateto  or year(datefrom) != year(dateto)) then
       return -1;
    end if;
    
    set days = 
       case 
       when week(dateto)-week(datefrom) = 0 then 
            dayofweek(dateto) - dayofweek(datefrom) + 1
          - case 
            when (dayofweek(datefrom) > 1 and dayofweek(dateto) < 7) then 0
            when (dayofweek(datefrom) = 1 and dayofweek(dateto) =7) then 2
            else 1
            end
       else (week(dateto)-week(datefrom)-1) * 5
          + case 
            when dayofweek(datefrom) = 1 then 5
            when dayofweek(datefrom) = 7 then 0
            else 7 - dayofweek(datefrom)
            end
          + case 
            when dayofweek(dateto) = 1 then 0
            when dayofweek(dateto) = 7 then 5
            else dayofweek(dateto) - 1
            end
       end;
             
       return days;
end$$
DELIMITER ;

测试:

 

标签:dayofweek,week,end,dateto,SQL,datefrom,when,MySQL,工作日
来源: https://www.cnblogs.com/shenyixin/p/14846556.html