2012-03-15 67 views
0

我需要計算日期之間的營業時間。在SQL中計算營業時間

我需要從那個小時中排除以下內容。

  1. 出的工作時間(18:00 -9am)
  2. 週末
  3. 假期

假期我有一個表節假日

 
DATE  NAME 
---------------------------------- 
2012-01-02 New Year's Day 
2012-04-06 Good Friday 
2012-04-09 Easter Monday 

注:
1。我在開始和結束日期('2012/03/15 14:00'至'2012/03/22 17:30')有幾個小時。
2.我使用Sql Server 2005,所以我沒有datetype DATE或TIME。

+0

http://stackoverflow.com/questions/5274208/calculate-business-hours-between-two-dates – kaj 2012-03-15 10:35:17

+0

@KAJ的可能重複檢查我問我的問題之前鏈接。正如我所提到的解決方案,提供了不適合我,因爲我需要計算小時,因爲我使用SQL Server 2005 – 2012-03-15 10:39:53

+1

沒有對這個問題,而不是所有的人不止一個解決方案依賴於日期/時間我不能使用DATE或TIME datetypes數據類型而不是日期時間這就是爲什麼我建議它 – kaj 2012-03-15 10:43:13

回答

3

試試這個。

DECLARE @start_date DATETIME 
DECLARE @stop_date DATETIME 
DECLARE @days INT 

SELECT @start_date = '2012/03/15 14:00', @stop_date = '2012/03/22 17:30' 

SELECT @days = DATEDIFF(DAY, CAST(FLOOR(CAST(@start_date AS FLOAT)) AS DATETIME), CAST(FLOOR(CAST(@stop_date AS FLOAT)) AS DATETIME)) + 1 

;WITH CTE_ALL_DAYS AS (
    SELECT TOP (@days) 
     DATEADD(DAY, rn, CAST(FLOOR(CAST(@start_date AS FLOAT)) AS DATETIME)) AS dt 
    FROM (
     SELECT ROW_NUMBER() OVER(ORDER BY (SELECT 1)) - 1 AS rn 
     FROM master.sys.all_columns AS a 
     CROSS JOIN master.sys.all_columns AS b 
     ) AS tally 
) 
SELECT SUM(
     CASE 
      WHEN dt = CAST(FLOOR(CAST(@start_date AS FLOAT)) AS DATETIME) THEN 
       CASE 
        WHEN DATEDIFF(HOUR, @start_date, DATEADD(HOUR, 18, CAST(FLOOR(CAST(@start_date AS FLOAT)) AS DATETIME))) > 9 THEN 9 
        WHEN DATEDIFF(HOUR, @start_date, DATEADD(HOUR, 18, CAST(FLOOR(CAST(@start_date AS FLOAT)) AS DATETIME))) > 0 THEN DATEDIFF(HOUR, @start_date, DATEADD(HOUR, 18, CAST(FLOOR(CAST(@start_date AS FLOAT)) AS DATETIME))) 
        ELSE 0 
       END 
      WHEN dt = CAST(FLOOR(CAST(@stop_date AS FLOAT)) AS DATETIME) THEN 
       CASE 
        WHEN DATEDIFF(HOUR, DATEADD(HOUR, 9, CAST(FLOOR(CAST(@stop_date AS FLOAT)) AS DATETIME)), @stop_date) > 9 THEN 9 
        WHEN DATEDIFF(HOUR, DATEADD(HOUR, 9, CAST(FLOOR(CAST(@stop_date AS FLOAT)) AS DATETIME)), @stop_date) > 0 THEN DATEDIFF(HOUR, DATEADD(HOUR, 9, CAST(FLOOR(CAST(@stop_date AS FLOAT)) AS DATETIME)), @stop_date) 
        ELSE 0 
       END 
      ELSE 9  
     END 
    ) 
FROM CTE_ALL_DAYS 
WHERE 
    NOT DATEPART(weekday, dt) IN (1, 7) 
    AND NOT dt IN (SELECT [DATE] FROM HOLIDAYS) 
+0

它返回48!這意味着它只能計算幾天而不是幾個小時。對不起,但這不是我所需要的。 – 2012-03-15 11:57:26

+0

remome SUM(),只留下CASE子句,然後你可以看到,48小時:4 + 9 + 9 + 9 + 9 + 8 – 2012-03-15 12:01:01

+0

我想,有上午9點到下午6個 – 2012-03-15 12:04:23