在MS SQL中,如何计算两个日期之间的时间,不包括晚上6点至晚上8点以及周末的晚上/晚上(非工作时间)的时间?
示例:
第1列:Time1: 2019-11-28 16:30:00
第2列:Time2: 2019-11-29 09:00:00
计算出的差异:1.5 h + 1 h = 2.5 h
答案 0 :(得分:0)
尝试一下:
declare @Column1 as smalldatetime, @Column2 as smalldatetime, @Column as smalldatetime
set @Column1 = '2019-11-28 16:30:00'
set @Column2 = '2019-11-29 09:00:00'
set @Column = @Column2
select
case
when DATEPART(DW, @Column) in (1, 7) then 0
when @Column <= dateadd(hour,18,cast(cast(@Column as date) as smalldatetime)) and @Column > dateadd(hour,9,cast(cast(@Column as date) as smalldatetime))
then datediff(minute, @Column, dateadd(hour,18,cast(cast(@Column as date) as smalldatetime)))
when @Column >= dateadd(hour,8,cast(cast(@Column as date) as smalldatetime)) and @Column < dateadd(hour,18,cast(cast(@Column as date) as smalldatetime))
then datediff(minute, dateadd(hour,8,cast(cast(@Column as date) as smalldatetime)), @Column)
end
答案 1 :(得分:0)
这是一个使用临时提示表的选项
CROSS APPLY将返回营业秒数,然后格式化就变得无关紧要。注意:您必须为24小时以上的物品留出余量。
示例
Declare @YourTable table (ID int,DT1 datetime,DT2 datetime)
Insert Into @YourTable values
(1,'2019-11-28 16:30:00','2019-11-29 09:00:00')
Select A.*
,Elapsed=format(dateadd(SECOND,Seconds,0),'HH:mm')
From @YourTable A
Cross Apply (
Select Seconds=sum(1)
From (Select Top (DateDiff(SECOND,DT1,DT2)+1) D=DateAdd(SECOND,-1+Row_Number() Over (Order By (Select Null)),DT1) From master..spt_values n1,master..spt_values n2) A
Where DateName(WEEKDAY,D) not in ('Saturday','Sunday')
and convert(time,D) > '08:00'
and convert(time,D) < '18:00'
) B
返回
ID DT1 DT2 Elapsed
1 2019-11-28 16:30:00.000 2019-11-29 09:00:00.000 02:30