Quantcast
Channel: Transact-SQL forum
Viewing all articles
Browse latest Browse all 23857

DATEADD and MAX() not working unless date is hardcoded

$
0
0

Can someone help me understand why using line 13 in the following code returns the wrong LAST_ENCOUNTER_DATE but lines 14 or 15 returns the correct date?  I cannot figure out why the hardcoded date or datetime works but not the item BTG_INSTANT.  I am running this code using SQL Server Mgmt Studio 2012.  CONTACT_DATE and BTG_INSTANT datatype is DATETIME.  I need to find the last CONTACT_DATE that is less than BTG_INSTANT.

select DISTINCT BTG.PAT_ID AS 'PAT ID'
,II.IDENTITY_ID AS 'BTG Patient MRN'
,BTG.LINE AS 'BTG LINE'
,BTG.BTG_INSTANT AS 'BTG INSTANT'
,LAST_ENC.LAST_ENCOUNTER_DATE AS 'LAST CONTACT DATE'
from PAT_BTG_AUDIT BTG
	INNER JOIN IDENTITY_ID II ON BTG.PAT_ID = II.PAT_ID AND II.IDENTITY_TYPE_ID = 1
	LEFT JOIN PATIENT EPT ON BTG.PAT_ID = EPT.PAT_ID
	LEFT JOIN (SELECT PE.PAT_ID 
		  ,MAX(PE.CONTACT_DATE) AS LAST_ENCOUNTER_DATE
			   FROM PAT_BTG_AUDIT PBA 
					INNER JOIN PAT_ENC PE ON PBA.PAT_ID = PE.PAT_ID
--LINE 13				AND PE.CONTACT_DATE < DATEADD(MM,@Months,PBA.BTG_INSTANT)
--LINE 14				AND PE.CONTACT_DATE < DATEADD(MM,@Months,'2014-03-02 13:53:00')
--LINE 15				AND PE.CONTACT_DATE < DATEADD(MM,@Months,'2014-03-02')
			   GROUP BY PE.PAT_ID) LAST_ENC ON EPT.PAT_ID = LAST_ENC.PAT_ID
WHERE CAST(BTG.BTG_INSTANT AS DATE) BETWEEN @BeginDate and @EndDate
	AND BTG.PAT_ID NOT IN (SELECT ENC.PAT_ID FROM PAT_ENC ENC
			       WHERE (ENC.CONTACT_DATE >= DATEADD(MM,@Months,BTG.BTG_INSTANT)
					AND ENC.CONTACT_DATE <= BTG.BTG_INSTANT)
				--EXCLUDE ENCOUNTER TYPES
				--5 Canceled
				--10 Empty
				--151 Erroneous Encounter
				OR ENC.ENC_TYPE_C IN (5,10,151))
AND II.IDENTITY_ID = '1325183'
ORDER BY BTG.PAT_ID, BTG.BTG_INSTANT, BTG.LINE


Viewing all articles
Browse latest Browse all 23857

Trending Articles