2011-01-22 64 views
1

我確定有人已經開發出了在其他編程語言中模擬Excel網絡日功能的工作。如果你可以分享的話,你可以選擇 。 感謝在sql中模擬Excel networkdays

+0

[MySQL的函數的可能的複製找到工作日內兩個日期之間的數](http://stackoverflow.com/questions/1828948/mysql-function-to-find-the-number-of-working-days-between-two-dates) – 2017-04-21 18:48:51

回答

3

的想法是計算每個日期的星期然後採用各種偏移的開始之間的工作日。

  1. 每個日期前找到週六之間的天數
  2. 除以7乘以5得到的工作日數
  3. 偏移總的起始日期是否是結尾日期
  4. 再次偏移量開始是否結束後開始是星期六
  5. 再次爲啓動是否是後到底是星期天
  6. 再次爲啓動以後是否不和開始是一個星期天
  7. 爲再次啓動後,是否不和,到底是週六

添加一些隨機的日期到表中。

declare @t table ([start] datetime, [end] datetime) 
insert into @t values ('2088-01-14 11:56:23','2011-11-10 03:34:09') 
insert into @t values ('2024-09-24 10:14:29','2087-09-16 15:52:06') 

然後爲這些日期計算NETWORKDAYS。

select [start],[end] 
    ,((datediff(day,0,[end])-datepart(dw,[end]))-(datediff(day,0,[start])-datepart(dw,[start])))/7*5 --[weekdays] 
    + datepart(dw,[end]) - datepart(dw,[start]) --[weekday diff] 
    + case when datediff(day,0,[start]) > datediff(day,0,[end]) then -1 else 1 end --[start after] 
    + case when datediff(day,0,[start]) > datediff(day,0,[end]) and datepart(dw,[start]) = 7 then 1 else 0 end --[start after and start saturday] 
    + case when datediff(day,0,[start]) > datediff(day,0,[end]) and datepart(dw,[end]) = 1 then 1 else 0 end --[start after and end sunday] 
    + case when datediff(day,0,[start]) <= datediff(day,0,[end]) and datepart(dw,[start]) = 1 then -1 else 0 end --[start not after and start sunday] 
    + case when datediff(day,0,[start]) <= datediff(day,0,[end]) and datepart(dw,[end]) = 7 then -1 else 0 end --[start not after and end saturday] 
    as [networkdays] 
    from @t 
+2

歡迎來到Stack Overflow!在答案中提供至少一個簡短的解釋和代碼是一個好主意。 – Techwolf 2012-11-08 06:32:03

0

對於它的價值,我創建了以下功能的MySQL,它假定週一至週五的工作日:

DROP FUNCTION IF EXISTS BusinessDays; 

DELIMITER // 

CREATE FUNCTION BusinessDays (startDate DATE, endDate DATE) 
RETURNS INT 
DETERMINISTIC 
BEGIN 
    DECLARE startWeekDay INT; 
    DECLARE allDays INT; 
    DECLARE fullWeekCount INT; 
    DECLARE remainderDays INT; 
    DECLARE maxPossibleRemainderWeekendDays INT; 
    DECLARE soloSundays INT; 
    DECLARE totalBusinessDays INT; 

    SET startWeekDay = WEEKDAY(startDate); 
    SET allDays = ABS(DATEDIFF(endDate, startDate)) + 1; 
    SET fullWeekCount = FLOOR(allDays/7); 
    SET remainderDays = allDays - (fullWeekCount * 7); 
    SET maxPossibleRemainderWeekendDays = ROUND(2*(startWeekDay+remainderDays-6)/(ABS(2*(startWeekDay+remainderDays-6))+1))+1; 
    SET soloSundays = ROUND(2*(startWeekDay-6)/(ABS(2*(startWeekDay-6))+1))+1; 

    SET totalBusinessDays = allDays - (fullWeekCount * 2) - maxPossibleRemainderWeekendDays + soloSundays; 
    RETURN totalBusinessDays; 
END // 

DELIMITER ;