| Author |
Topic |
|
qazxi
Starting Member
1 Post |
Posted - 2005-03-14 : 04:20:58
|
| Hi I want to calculate the time difference between two dates but hours out of business hours must be excluded. Also beginning or end date could be out of business hours. |
|
|
rockmoose
SQL Natt Alfen
3279 Posts |
Posted - 2005-03-14 : 06:03:49
|
This makes use of 2 "number tables", one for days, and one for hours.declare @d1 datetime, @d2 datetimeselect @d1 = dateadd(hh,-43,getdate()), @d2 = getdate()select sum( case when hrs.number between 7 and 19 then 1 else 0 end ) as bzns_hrs ,count(*) as tot_hrsfrom master.dbo.spt_values dys cross join master.dbo.spt_values hrswhere dys.type = 'P' and hrs.type = 'P' and hrs.number between 0 and 23 and dys.number <= datediff(day,@d1,@d2) and case when dys.number = 0 then hrs.number else 24 end >= datepart(hh,@d1) and case when dys.number = datediff(day,@d1,@d2) then hrs.number else 0 end <= datepart(hh,@d2)-- this just displays the data used to sum the hours between @d1 and @d2select @d1 as d1,@d2 as d2,dys.number,hrs.numberfrom master.dbo.spt_values dys cross join master.dbo.spt_values hrswhere dys.type = 'P' and hrs.type = 'P' and hrs.number between 0 and 23 and dys.number <= datediff(day,@d1,@d2) and case when dys.number = 0 then hrs.number else 24 end >= datepart(hh,@d1) and case when dys.number = datediff(day,@d1,@d2) then hrs.number else 0 end <= datepart(hh,@d2)order by 1,2,3,4 rockmoose |
 |
|
|
spirit1
Cybernetic Yak Master
11752 Posts |
Posted - 2005-03-14 : 06:17:21
|
no numbers table  declare @Start datetime, @End datetimeselect @Start = dateadd(n, 10, getdate()-3), @end = dateadd(n, 0, getdate())select @Start, @End, ( case when DATEPART (hour, @Start) between 8 and 15 then datediff(n, @Start, DATEADD(d, DATEDIFF(d, 0, @Start), 0) + '16:00:00') -- number of hours until 16:00 else 0 end+ case when DATEPART (hour, @End) between 8 and 15 then datediff(n, DATEADD(d, DATEDIFF(d, 0, @End), 0) + '08:00:00', @End) -- number of hours after 08:00 else 0 end+datediff (d, DATEADD(d, DATEDIFF(d, case when DATEPART (hour, @End) between 8 and 15 then 0 else 1 end, @Start), 0), DATEADD(d, DATEDIFF(d, 1, @End), 0))*8*60 -- number of working hours * minutes)/60.00 as diff Go with the flow & have fun! Else fight the flow |
 |
|
|
rockmoose
SQL Natt Alfen
3279 Posts |
Posted - 2005-03-14 : 06:58:53
|
>> no numbers table And you only work 8-15 as well, darn !rockmoose |
 |
|
|
spirit1
Cybernetic Yak Master
11752 Posts |
Posted - 2005-03-14 : 07:35:42
|
my hours are very flexible... but this is for 8 to 16 work day. its >= lower and < higher.Go with the flow & have fun! Else fight the flow |
 |
|
|
|
|
|