In my new role I have inherited the following SQL statement:
DECLARE @StartDate DATETIME = '2014-12-1'
SELECT
ROW_NUMBER() OVER(ORDER BY ORDERS.ORDERDATE, PatientProfile.searchname) as RowNumber
, PatientProfile.searchname as PatientName
, PatientProfile.Birthdate
, ORDERS.ORDERDATE as OrderDate
, DATEDIFF(D, ORDERS.ORDERDATE, ORDERS.DB_UPDATED_DATE) AS DaysToCurrentStatus
, ORDERS.DESCRIPTION as ReferralType
, CASE WHEN ORDERS.STATUS = 'U' Then 'Unsigned'
WHEN ORDERS.STATUS = 'H' Then 'Admin Hold'
WHEN ORDERS.STATUS = 'S' Then 'InProcess'
WHEN ORDERS.STATUS = 'C' Then 'Complete'
WHEN ORDERS.STATUS = 'X' Then 'Cancelled'
ELSE NULL END AS Status
, df.ListName as OrderingProvider
, ORDERS.DB_UPDATED_DATE as LastUpdated
, ORDERS.CLINCOMMENTS as Comments
, RIGHT(RTRIM(REPLACE(REPLACE(ORDERS.CLINCOMMENTS,CHAR(10),''),CHAR(13),'')), 18) as AppointmentDate /* Get rid of carriage returns, line breaks, and trailing spaces */
, Coordinator = CASE
WHEN ORDERS.ADMINCOMMENTS like 'Leticia%' then 'Leticia'
WHEN ORDERS.ADMINCOMMENTS = 'Je%' then 'Jessica'
WHEN ORDERS.ADMINCOMMENTS = 'Da%' then 'Dahlia'
WHEN ORDERS.ADMINCOMMENTS = 'sandra' OR ORDERS.ADMINCOMMENTS = 'sc' THEN 'Sandra'
ELSE NULL END
, LOCREG.ABBREVNAME as Location
INTO #TEMP
FROM (CentricityPS.dbo.PatientProfile PatientProfile
INNER JOIN CentricityPS.dbo.ORDERS ORDERS
ON PatientProfile.PId=ORDERS.PID)
INNER JOIN DoctorFacility df
ON ORDERS.AUTHBYUSRID = DF.PVId
INNER JOIN CentricityPS.dbo.LOCREG LOCREG
ON DF.LocationId=LOCREG.LOCID
WHERE ORDERS.ORDERDATE >= @StartDate
AND ORDERS.ORDERTYPE='R' /*Referral*/
AND ORDERS.XID= 1000000000000000000
ORDER BY OrderingProvider
/* Cast only valid dates as AppointmentDates*/
SELECT RowNumber, CAST(AppointmentDate as DateTime) as AppointmentDate
INTO #Appts
FROM #TEMP
WHERE ISDATE(AppointmentDate) = 1
SELECT
t.PatientName
, t.Birthdate
, t.OrderDate
, t.ReferralType
, t.Status
, t.OrderingProvider
, t.Comments
, a.AppointmentDate as AppointmentDate
, DATEDIFF(D, a.AppointmentDate, GETDATE()) as DaysSinceApptDate
, t.Coordinator
, t.Location
FROM #TEMP t
LEFT JOIN #Appts a
ON a.RowNumber = t.RowNumber
DROP TABLE #TEMP, #Appts
The results I receive from this line ', DATEDIFF(D, a.AppointmentDate, GETDATE()) as DaysSinceApptDate' in the query returns negative values. I do not wish to have negative values in my results. Is there a way to re-write this statement without affecting the rest of the data?