Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2008 Forums
 Transact-SQL (2008)
 datediff

Author  Topic 

inbs
Aged Yak Warrior

860 Posts

Posted - 2012-12-18 : 06:48:27
i want to know the hours between two dates?
the work hours is between 08:00-18:00

i have two columns


StartDate closeDate Hours
'2012-12-18 08:00:00','2012-12-18 10:00:00' 2
'2012-12-18 07:00:00','2012-12-18 10:00:00' 2
'2012-12-18 07:00:00','2012-12-18 20:00:00' 10
'2012-12-18 08:00:00','2012-12-19 10:00:00' 12
'2012-12-18 07:00:00','2012-12-20 10:00:00' 22

bandi
Master Smack Fu Yak Hacker

2242 Posts

Posted - 2012-12-18 : 08:01:28
Simple way is:

DECLARE @timeDiff TABLE(StartDate datetime, closeDate DATETIME)
insert into @timeDiff
SELECT '2012-12-18 08:00:00','2012-12-18 10:00:00' union all
SELECT '2012-12-18 07:00:00','2012-12-18 10:00:00' union all
SELECT '2012-12-18 07:00:00','2012-12-18 20:00:00' union all
SELECT '2012-12-18 08:00:00','2012-12-19 10:00:00' union all
SELECT '2012-12-18 07:00:00','2012-12-20 10:00:00'

;with cte AS
(
SELECT CASE WHEN DATEPART(HH, startDate) < 8 THEN 8 ELSE DATEPART(HH, startDate) END startTime,
CASE WHEN DATEPART(HH, closeDate) >= 18 THEN 18 ELSE DATEPART(HH, closeDate) END EndTime,
DATEDIFF(dd, startDATE, CloseDate) noOfDays,
StartDate,
closeDate
FROM @timeDiff
)SELECT (endtime *(noOfDays+1) - startTime) , StartDate, closeDate FROM cte


For more accuracy check this link
http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=176582

--
Chandu
Go to Top of Page
   

- Advertisement -