从两个表中加入两个最近的事件

时间:2014-07-03 15:45:54

标签: sql sql-server join subquery medical

我正在尝试在SQL中构建一个报告,显示患者上次收到特定实验室服务的时间以及他们收到该服务的设施。不幸的是,实验室程序和设施位于不同的表格中。这就是我现在所拥有的(事先为我奇怪的别名道歉,因为实际的表名更好):

;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

我的问题是,如果患者在时间范围内去过多个设施,子查询将选择每个设施进入连接,通过apprx 4000扩大结果。我需要找到一种方法来选择约会列表中非常最近的设施,然后将其加入实验室。实验室没有visitID(这很有意义)。我相信我在子查询选择或相应的连接中都缺少某些东西,但在四天之后我觉得我需要专业的帮助。

非常感谢您的建议,请让我知道我可以澄清的地方。提前谢谢!

1 个答案:

答案 0 :(得分: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()窗口函数。 “分区依据”和“排序依据”条款保证您将为每位患者获取一组行号,并且具有最新日期的行将被分配第1行。“seqnum = 1”的过滤器确保您获得每个患者只需要一行