我想获得2个日期时间之间经过的小时数,但不包括周末。
所以我想说我有2014-03-28 07:45:00(这是星期五)和2014-04-04 09:45:00(这是星期五) 我想弄清楚两个日期之间经过了多少小时但排除了周末。
我不知道如何继续,但我找到了http://www.codersrevolution.com/blog/SQL-Server-How-Many-WorkWeek-Days-In-Date-Range
找工作日的链接答案 0 :(得分:2)
创建一个功能:
create function f_hour_diff (@date1 datetime,@date2 datetime)
returns int
as
begin
-- if @date1 happens on the weekend, set to next Monday 12AM
if datepart(weekday,@date1) = 1
set @date1 = dateadd(day,datediff(day,0,@date1),1)
if datepart(weekday,@date1) = 7
set @date1 = dateadd(day,datediff(day,0,@date1),2)
-- if @date2 happens on the weekend, set to previous Saturday 12AM
-- to count all of Friday's hours
if datepart(weekday,@date2) = 1
set @date2 = dateadd(day,datediff(day,0,@date2),-2)
if datepart(weekday,@date2) = 7
set @date2 = dateadd(day,datediff(day,0,@date2),-1)
-- return number of hours between @date1 and @date1
-- subracting the number of weeks between * 48 to take out weekends
declare @return int
set @return = datediff(hour,@date1,@date2)-(datediff(week,@date1,@date2)*48)
-- Return the result of the function
return @return
end
go
调用函数:
select dbo.f_hour_diff('2014-03-28 07:45:00','2014-04-04 09:45:00')