Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Calculate visits based on cutoff date 1

Status
Not open for further replies.

briangriffin

Programmer
Nov 6, 2008
878
US
I have a group of patients participating in a special program. I need to compute the number of hospital visits for each patient before and after they joined this program.

Patient table looks like this:

Code:
PatientID      ActiveDate           InactiveDate          PreActiveVisits
111              7/1/2016           12/31/2016                   ?

Visits table looks like this:

PatientID           AdmitDate
111                 1/1/2016
111                 2/1/2016
111                 3/1/2016
111                 8/1/2016

Need to populate the Patient table with a PreActiveVisits total of 3 but I'm not sure how to approach this without using a cursor.

 
Would this query return the correct data?

Code:
Select  Visits.PatientId,
        Count(Visits.AdmitDate) As PreActiveVisits
From    Patient
        Inner Join Visits
          On Patient.PatientId = Visits.PatientId
          And Patient.ActiveDate <= Visits.AdmitDate
Group By Visits.PatientId

-George
Microsoft SQL Server MVP
My Blogs
SQLCop
twitter
"The great things about standards is that there are so many to choose from." - Fortune Cookie Wisdom
 
Try something like this:

Code:
WITH VisitCount (PatientID, VCount) AS
  (SELECT Visits.PatientID, COUNT(AdmitDate) 
     FROM Visits 
       JOIN Patient
         ON Visits.PatientID = Patient.PatientID
     WHERE Visits.AdmitDate < Patient.ActiveDate))

UPDATE Patient
  SET PreActiveVisits = VisitCount.VCount
  WHERE Patient.PatientID = VisitCount.PatientID

Tamar
 
That did it - as always you make it look easy. For the update it would be easiest to use this as a cte? Thanks.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top