SQL calaulate start time and end time between a date range

I need to calculate a start and end time between a date range.   This gives the date range and the different times.  I need Patient.AnesStartTime and Patient.EndStartTime calculated to show how much time for each patient between the date range.

SELECT     AnesStaff.AnesLastName, AnesStaff.AnesFirstName, Service.Service, Service.MEPERSCode, AnesStaff.FlagRelief, Patient.DateSurgery, Patient.AnesStartTime,
                      Patient.AnesEndTime
FROM         Service INNER JOIN
                      AnesStaff ON Service.PatientID = AnesStaff.PatientID INNER JOIN
                      Patient ON Service.PatientID = Patient.PatientID AND AnesStaff.PatientID = Patient.PatientID
WHERE     (Patient.DateSurgery BETWEEN CONVERT(DATETIME, '2008-03-01 00:00:00', 102) AND CONVERT(DATETIME, '2008-04-01 00:00:00', 102))

ThanksScreenshot
JohnMac328Asked:
Who is Participating?
 
ste5anSenior DeveloperCommented:
hmm, DateSurgery should be a DATE, not DATETIME. AnesStartTime and AnesEndTime should be TIME. You need to check whether constraints exists on these columns to ensure their domain. Otherwise you may get wrong results.

When to model is ok, then you simply use DATEDIFF() to calculate a [DATE]TIME difference.

SELECT  AnS.AnesLastName ,
        AnS.AnesFirstName ,
        S.Service ,
        S.MEPERSCode ,
        AnS.FlagRelief ,
        P.DateSurgery ,
        P.AnesStartTime ,
        P.AnesEndTime ,
        DATEDIFF(MINUTE, P.AnesStartTime, P.AnesEndTime) AS AnesTimeDifferenceInM
FROM    [Service] S
        INNER JOIN AnesStaff AnS ON S.PatientID = AnS.PatientID
        INNER JOIN Patient P ON S.PatientID = P.PatientID
                                AND AnS.PatientID = P.PatientID
WHERE   P.DateSurgery BETWEEN '20080301' AND '20080401';

Open in new window


Caveat: The result of DATEDIFF() is a date/time range. There is no built-in data type nor formatting in SQL Server. Thus the result is an integer in the chosen resolution (here minutes).

p.s. use always table alias names. It increases readability.

p.p.s. instead of using CONVERT() on constants, use an unambiguous date literal like 'yyyymmdd'.
0
 
JohnMac328Author Commented:
Thanks that seems to work.  I agree with your statements but this is a deployed system and those changes are not allowed since it has been sunsetted.  I have seen other reports with the times displaying like your example shows.  Reports are still allowed.
0
 
JohnMac328Author Commented:
Thanks again
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.