在sql中选择对一个属性具有最大值的记录,该属性小于另一个属性

时间:2014-08-21 06:10:50

标签: mysql sql sql-server sql-server-2008 database-design

我有一张表MyTable,其中的属性为:

  

Id(PK)

     

patientId(int)

     

Transfusion_Date(datetime)

     

checkup_date(datetime)

     

血红蛋白_水平(浮动)

对于每个checkup_date,都有一个唯一的haemoglobin_level, 一个patientId可以包含多个Transfusion_Date以及多个checkup_date (此处checkup_date表示衡量haemoglobin_level的日期)

我需要检索记录,以便在haemoglobin_level

之前获得特定patientId的{​​{1}}(s)

请帮我完成我必须写的查询。

2 个答案:

答案 0 :(得分:0)

这将为myPatId的{​​{1}}提供一条或多条记录,该记录位于您指定的checkup_date之前。

myTransfusionDate

答案 1 :(得分:0)

declare @PatientId int;

declare @MyTable table (
    Id int primary key,
    patientId int,
    Transfusion_Date datetime,
    checkup_date datetime,
    haemoglobin_level float
);

select *
from @MyTable t
where t.patientId = @PatientId
    and t.checkup_date <= t.Transfusion_Date
    and not exists (
        select 0 from @MyTable t2
        where t2.patientId = t.patientId
            and t2.checkup_date between t.checkup_date and t.Transfusion_Date
    );