試試這個。
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)
http://stackoverflow.com/questions/5274208/calculate-business-hours-between-two-dates – kaj 2012-03-15 10:35:17
@KAJ的可能重複檢查我問我的問題之前鏈接。正如我所提到的解決方案,提供了不適合我,因爲我需要計算小時,因爲我使用SQL Server 2005 – 2012-03-15 10:39:53
沒有對這個問題,而不是所有的人不止一個解決方案依賴於日期/時間我不能使用DATE或TIME datetypes數據類型而不是日期時間這就是爲什麼我建議它 – kaj 2012-03-15 10:43:13