2017-05-04 32 views
1

例如,我們有日期2017/5/4 01:00:00 PM在工作日我們有工作時間08:00至17:30如何計算SLA日期和時間?分配如何從SQL中指定的日期計算業務日期和時間

日期:2017年5月4日下午1點00分零零秒

如果SLA是指定日期8小時。

截止日期應該是:2017/5/5 11:30:00 AM排除週末和非營業時間。

+0

我不是很確定。 SLA的立場是什麼?不能使用'DateTimeAddHours'方法嗎? –

+0

@MightyBadaboom SLA =服務水平協議。在這種情況下,它指的是他們同意提供答覆的時間。 – iamdave

+0

啊,好的。感謝您的信息:)但對於我來說,目前仍不清楚「日期指定」是什麼意思。 –

回答

0

這是一個非常複雜的問題,我認爲你是因爲它。有許多天和時間會超出工作時間,您需要考慮。這將包括任何假期,半天,辦公室關閉等。這最好通過維護被認爲是工作時間的日期,小時甚至分鐘表來處理。

如果你不想只爲這一個表,一個簡單的Dates表再加當一個特定的日期或時間被認爲是工作時間與否的規則,第二臺可以讓你得到這個。

如果你甚至不用說,你將需要你想運行您的查詢,每次派生表包括所有的這個查詢中規則的工作時間。創建datetime值表的最有效的方法是理貨表,而你的情況可以如下利用:

declare @DateAssigned datetime = '05-04-2017 13:00:00'; 
declare @DayStart time = '08:00:00'; 
declare @DayEnd time = '17:30:00'; 
declare @SLAMinutes int = 480; -- 8 hours * 60 minutes per hour 


     -- cte to create a table with 10 rows in 
with n(n) as (select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1 union all select 1) 
     -- cte to cross join the rows together, resulting in 10^6 (1 million) rows. Add or remove joins per number of minutes required. 
     -- Use the row_number function to add an incremental number of minutes to the original @DateAssigned to get a table of minutes from the @DateAssigned value. 
    ,t(t) as (select dateadd(minute,row_number() over(order by (select null))-1,@DateAssigned) from n n1, n n2, n n3, n n4, n n5, n n6) 
     -- Select the first @SLANumber number of rows that meet your Working Time criteria. We add 2 to this value do resolve the fencepost problem. 
    ,d(d) as (select top (@SLAMinutes + 2) t 
       from t 
       where cast(t as time) >= @DayStart  -- Only return minutes from 08:00 onwards. 
       and cast(t as time) <= @DayEnd  -- Only return minutes up to 17:30. 
       and datepart(weekday,t) not in (7,1) -- Only return minutes not on Saturday or Sunday. 
       order by t) 
    -- The MAX value in the cte d will be the last minute of your SLA window. 
select @DateAssigned as DateAssigned 
     ,max(d) as SLADeadline 
from d; 

,輸出:

+-------------------------+-------------------------+ 
|  DateAssigned  |  SLADeadline  | 
+-------------------------+-------------------------+ 
| 2017-05-04 13:00:00.000 | 2017-05-05 11:30:00.000 | 
+-------------------------+-------------------------+