①
CREATE DEFINER=`root`@`%` FUNCTION `WORKDAYSONEYEAR``datefrom` datetime,`dateto` datetime) RETURNS int20) NO SQL BEGIN declare days int default 1; # 如果起始时间大于结束时间或者日期跨年那么直接返回-1,表示不支持 if datefrom > dateto or yeardatefrom) != yeardateto)) then return -1; end if; set days = case # 同一周的情况:计算时间间隔再减去周六周日的天数 # 每周开始时间为星期日,1是星期日 7是星期六 when weekdateto)-weekdatefrom) = 0 then dayofweekdateto) - dayofweekdatefrom) + 1 - case when dayofweekdatefrom) > 1 and dayofweekdateto) < 7) then 0 when dayofweekdatefrom) = 1 and dayofweekdateto) =7) then 2 else 1 end #不是同一周的情况:间隔周数 * 5 加上同一周的工作日 else weekdateto)-weekdatefrom)-1) * 5 + case when dayofweekdatefrom) = 1 then 5 when dayofweekdatefrom) = 7 then 0 else 7 - dayofweekdatefrom) end + case when dayofweekdateto) = 1 then 0 when dayofweekdateto) = 7 then 5 else dayofweekdateto) - 1 end end; return days; end
②
CREATE DEFINER=`root`@`%` FUNCTION `WORKDAYSTWOYEARS``startdate` datetime,`enddate` datetime) RETURNS int20) BEGIN #起始时间大于结束时间,直接返回-1,表示不支持 if startdate > enddate) then return -1; #同一年的情况下,直接使用上面的WORKDAYSONEYEAR)函数计算 ELSEIF yearstartdate) = yearenddate)) then set @days = WORKDAYSONEYEARstartdate,enddate); return @days; #年份相差一年,分两段进行处理 ELSEIF yearstartdate) < yearenddate)) then set @yearofstartdate = yearstartdate); set @yearofenddate = yearenddate); set @lastdayofstartdate = CONCAT@yearofstartdate,'-12-31'); set @intervelone = WORKDAYSONEYEARstartdate,@lastdayofstartdate); set @days = @intervelone; set @firstdayofenddate = CONCAT@yearofenddate,'-01-01'); set @interveltwo = WORKDAYSONEYEAR@firstdayofenddate,enddate); set @days = @intervelone + @interveltwo; end if; return @days; end
测试:
select WORKDAYSTWOYEARS'2019-12-15','2020-01-05');