你留下了一些細節你的問題:
- 其中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'