Link to home
Start Free TrialLog in
Avatar of Jeff S
Jeff SFlag for United States of America

asked on

SQL Query to check if patient seen in prior 3 years

The following query returns all my patients seen by the practice for a given day (PatientVisitId for the Patient Visit and the PatientProfileId for the distinct patient). What I need is a field added to my final select query that tells me if my distinct patient has had another PatientVisitId in the prior 3 years. Maybe a CASE statement that provides me with a 1 or a 0?

CASE WHEN .... (seen in past 3 years) THEN 1 ELSE 0 END

Hope this makes sense.

SET NOCOUNT ON

DECLARE @DATETYPE VARCHAR(3) = 'DOS'
DECLARE @STARTDATE DATETIME = '09/22/2016'
DECLARE @ENDDATE   DATETIME = '09/22/2016'

CREATE TABLE #Visits 
	(
		   PatientVisitId INT
		 , PatientProfileId INT 
	 ) ;

INSERT INTO #Visits 
	(
		  PatientVisitId
		, PatientProfileId 
	) 
	
SELECT DISTINCT
	  pv.PatientVisitId
	, pv.PatientProfileId
FROM
	PatientVisitProcs pvp 
	JOIN PatientVisit pv ON pv.PatientVisitId = pvp.PatientVisitId
WHERE 
	ISNULL ( pvp.voided , 0 ) = 0  --filter out voided visits
    AND (@DATETYPE = 'DOS' AND pvp.DateofServiceFrom >= @STARTDATE AND pvp.DateofServiceFrom < DATEADD(D , 1 , @ENDDATE)
      OR @DATETYPE = 'DOE' AND pvp.DateofEntry >= @STARTDATE AND pvp.DateofEntry < DATEADD(D , 1 , @ENDDATE))
      
 SELECT 
	  v.PatientVisitId
	, v.PatientProfileId
FROM #Visits v
 
 DROP TABLE #Visits     

Open in new window

SOLUTION
Avatar of Arifhusen Ansari
Arifhusen Ansari
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial