你留下了一些细节你的问题:
- 其中MS SQL Server版本所使用。我假定SQL2005或更新的版本,以便可以使用CTE和排名函数ROW_NUMBER()。
- 无论您是希望给定患者的每次观察的最新值,还是希望在最近一次观察到的患者的所有值都对患者进行了任何观察。我假设前者。
该查询应该给你的总体思路:
with WindowedObservation as (
select Patient_oid, FindingAbbr, Value, CreationTime,
row_number() over (
partition by Patient_oid, FindingAbbr
order by CreationTime desc
) as ROWNUM
from HObservation
)
select *
from WindowedObservation
join HPatient
on HPatient.ObjectId = WindowedObservation.Patient_oid
where WindowedObservation.ROWNUM = 1
注释掉WHERE子句来看看是如何被使用ROW_NUMBER()。
下面是示例数据少量来测试:
CREATE TABLE HPatient (
ObjectId int,
Name nvarchar(50)
)
insert into HPatient(ObjectId, Name)
select 1,'Patient1'
union all select 2, 'Patient2'
union all select 3,'Patient3'
CREATE TABLE HObservation (
Patient_oid int,
FindingAbbr nvarchar(50),
Value float,
CreationTime datetime
)
insert into HObservation(Patient_oid, FindingAbbr, Value, CreationTime)
select 1, 'A_Pulse', 64, '2012-01-01'
union all select 1, 'A_Pulse', 73, '2012-01-02'
union all select 1, 'A_Pulse', 59, '2012-01-03'
union all select 1, 'A_Temperature', 98.6, '2012-01-01'
union all select 1, 'A_Temperature', 98.1, '2012-01-02'
union all select 1, 'A_Temperature', 90.2, '2012-01-03'
union all select 2, 'A_Pulse', 61, '2012-01-03'
union all select 2, 'A_Pulse', 67, '2012-01-04'
union all select 2, 'A_Pulse', 64, '2012-01-05'
union all select 2, 'A_Temperature', 100.2, '2012-01-03'
union all select 2, 'A_Temperature', 98.6, '2012-01-04'
union all select 2, 'A_Temperature', 98.9, '2012-01-05'
union all select 3, 'A_Pulse', 80, '2012-02-01'
union all select 3, 'A_Temperature', 98.2, '2012-02-01'
union all select 3, 'Wt', 180, '2012-02-01'
union all select 3, 'A_Pulse', 84, '2012-02-02'
union all select 3, 'A_Respirations', 16, '2012-02-03'