0

我停了下来,我在mysql中做了一个计算小时数的函数,但它一直给我错误的数字,我已经看了好几个小时了,我只是看不出我做错了什么

FUNCTION `WorkingHours`(`stardate` TIMESTAMP, `enddate` TIMESTAMP) RETURNS int(11)
BEGIN
DECLARE result DECIMAL(20,10) DEFAULT 0;
DECLARE TotWeeks DECIMAL(20,10);
DECLARE FullWeeks INT;
DECLARE RestDays DECIMAL(20,10);
DECLARE StartDay INT DEFAULT WEEKDAY(stardate) + 1;
SET TotWeeks = (TIMESTAMPDIFF(HOUR,stardate,enddate))/(24*7);
SET FullWeeks = FLOOR(TotWeeks);
SET RestDays = ROUND((TotWeeks-FullWeeks) * 7);
IF(RestDays + StartDay) > 5 THEN SET result = ROUND((TotWeeks*7*24) - (FullWeeks*2*24 + (((RestDays + StartDay) - 5) * 24)));
ELSE SET result = ROUND((TotWeeks*7*24) - (FullWeeks*2*24));
END IF;
RETURN result;
END

如果有人有任何建议或替代方法,我非常乐意替换这个。

Startdate:2017-07-05 12:17:18
Enddate:2017-07-07 18:30:42

给我 - 5

编辑: 这些日期给出-45

Startdate:2017-07-09 13:55:41
Enddate:2017-07-10 17:31:56

该功能几乎每次都可以正常工作,但有几次没有,我只是不知道为什么

4

1 回答 1

1

好的,我越过了一个可以满足您需求的功能。它只是计算日期范围的工作日。

DELIMITER $$

CREATE FUNCTION `CountWeekDays` (sdate VARCHAR(50), edate VARCHAR(50)) RETURNS INT

BEGIN
    #  first some variables for our procedure/function...
    DECLARE wdays, tdiff, counter, thisday smallint;
    DECLARE newdate DATE;
    #  now loop from start to end counting the loops and the number of weekdays...

    SET newdate := sdate;
    SET wdays = 0;

    #  return 1 if they're the same for "same day service"...
    if DATEDIFF(edate, sdate) = 0 THEN RETURN 1; END IF;
    #  if they're negative, return zero...
    if DATEDIFF(edate, sdate) < 0 THEN RETURN 0; END IF;

    label1: LOOP
        SET thisday = DAYOFWEEK(newdate);
        IF thisday BETWEEN 2 AND 6 THEN SET wdays := wdays + 1; END IF;
        SET newdate = DATE_ADD(newdate, INTERVAL 1 DAY);
        IF DATEDIFF(edate, newdate) < 0 THEN LEAVE label1; END IF;
    END LOOP label1;

    RETURN wdays;
END $$

DELIMITER ;

我在这里找到了这个功能。

然后使用它,这里有一些示例运行。请注意,时间部分实际上并不重要,因为该函数使用日期部分。

select CountWeekDays('2017-07-05', CURRENT_TIMESTAMP) * 24 as WorkingHours

在此处输入图像描述

select CountWeekDays('2017-07-09 13:55:41', '2017-07-10 17:31:56') * 24 as WorkingHours

在此处输入图像描述

select CountWeekDays('2017-07-05', '2017-07-07') * 24 as WorkingHours

在此处输入图像描述

select CountWeekDays('2017-07-08', '2017-07-09') * 24 as WorkingHours

在此处输入图像描述

select CountWeekDays('2017-07-07', '2017-07-10') * 24 as WorkingHours

在此处输入图像描述

所以试试看,看看你的想法。您可以删除* 24查询部分以查看任何给定日期范围的工作日计数。

于 2017-07-11T18:02:50.340 回答