[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 264
  • Last Modified:

TSQL update query syntax

Hello,

SQL Server 2008.

I have a table of patients called Patients where each patient is identified by PatientId.

I have a table of visits called Visits where each visit has the PatientId and a the visit date.  There is also a unique id column in the Visit table.


I want to search the Visits table, look up the latest visit date and id for each patient in the Patients table, and update the Patient table with this values.

I am trying to use the following general syntax:

update #Patients set LatestVisit = h.VisitDate, Id = h.id from
 (select top 1 fd.PersonId, fd.id, fd.VisitDate from dbo.Trombos_FollowUpData fd 
 order by fd.Visitdate desc ) h
where h.Personid = #Patients.PersonId

Open in new window

but i see i need to add a where statement in the inner select somehow to match the patients.

Maybe i need to do this using an inner join?
0
soozh
Asked:
soozh
1 Solution
 
Ioannis ParaskevopoulosCommented:
Hi,


Try this:


;WITH MyCTE AS
(
    SELECT  fd.PersonId, 
                  fd.id, 
                  fd.VisitDate,
                  ROW_NUMBER() OVER(PARTITION BY fd.PersonId ORDER BY fd.VisitDate DESC) AS RowNum
    FROM   dbo.Trombos_FollowUpData fd 
)

UPDATE    #Patients 
SET           LatestVisit = h.VisitDate, 
                 Id = h.id
FROM       #Patients P
                 JOIN MyCTE h
                     ON h.Personid = P.PersonId
WHERE    RowNum = 1

Open in new window


The above will create a CTE which will have an integer column in each row. This column(RowNum) will have an increasing value for each Patient based on the visit date. The latest Visitdate for Patient 1 would have a RowNum 1 and the latest VisitDate for patient 2 will also have RowNum = 1. This way you can get the latest Visit Date for each Patient and then use it to update accordingly.

Giannis
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now