0

I'm trying to build a report in SQL that shows when a patient last received a particular lab service and the facility at which they've received that service. Unfortunately, the lab procedure and facility are in different tables. Here is what I have now (apologies in advance for my weird aliasing, it makes better since with the actual table names):

;with temp as (Select distinct flow.pid, flow.labdate as obsdate, flow.labvalue as obsvalue
            From labstable as flow 
            Where flow.name = 'lab name' 
        )
Select distinct p.patientid, MAX(temp.obsdate) [Last Reading], COUNT(temp.obsdate) [Number of Readings], 
Case 
When count(temp.obsdate) > 2 then 'Active'Else 'Inactive' End [Status], facility.NAME [Facility]

From Patientrecord as p 
Join temp on temp.pid = p.PId
Join (Select loc.name, MAX(a.apptstart)[Last appt], a.patientid
    From Appointmentstable as a 
    Join Facility as loc on loc.facilityid = a.FacilityId
    Where a.ApptStart = (Select MAX(appointments.apptstart) from Appointments where appointments.patinetId = a.patientid)
    Group by loc.NAME, a.patientId
    ) facility on facility.patientId = p.PatientId

Group by p.PatientId, facility.NAME
Having MAX(temp.obsdate) between DATEADD(yyyy, -1, GETDATE()) and GETDATE()
Order by [Last Reading] asc

My problem with this is that if the patient has been to more than one facility within the time frame, the subquery is selecting each facility into the join, inflating the results by apprx 4000. I need to find a way to select ONLY the VERY MOST RECENT facility from the appointments list, then join it back to the lab. Labs do not have a visitID (that would make too much sense). I'm fairly confident that I'm missing something in either my subquery select or the corresponding join, but after four days I think I need professional help.

Suggestions are much appreciated and please let me know where I can clarify. Thank you in advance!

4

1 回答 1

0

将别名为“facility”的子查询更改为如下内容:

...
join (
select patientid, loc_name, last_appt
from (
    select patientid, loc_name=loc.name, last_appt=apptstart, 
        seqnum=row_number() over (partition by patientid order by apptstart desc)
    from AppointmentsTable a
    inner join Facility loc on loc.facilityid = a.facilityid
) x
where seqnum = 1
) facility
on ...
...

关键区别在于 row_number() 窗口函数的使用。“partition by”和“order by”子句保证您将获得每位患者的一组行号,并且最近日期的行将被分配行号 1。“seqnum = 1”的过滤器确保您得到每个患者只需要一行

于 2014-07-03T15:58:10.010 回答