需要上一年的最后价值

时间:2016-02-13 15:19:26

标签: sql-server tsql sql-server-2012

我正在尝试查询患者2015年的最后血压值。

当我使用max(date)时,它包含2016年的值,但是当我应用where date < '2016-01-01'时,它不会在2015年为我提供这些患者的值,而只是将其从结果中删除。

到目前为止的查询:

select distinct 
    pat.pat_last_name, 
    pat.pat_first_name, 
    pat.birth_date, 
    enc.bmi, 
    enc.contact_date, 
    enc.[weight], 
    enc.height, 
    pat.PAT_ID 
from 
    pat_enc enc 
    inner join patient pat on enc.pat_id = pat.pat_id 
    inner join (
        select pat_id, max(contact_date) as LastEncounter 
        from pat_enc 
        group by pat_id
        ) enc2 on enc.pat_id = enc2.pat_id and enc.contact_date = enc2.lastencounter 
where 
    enc.contact_date < '2016-01-01' and 
    enc.bmi is not null 
group by 
    pat.pat_last_name, 
    pat.PAT_FIRST_NAME, 
    pat.birth_date, 
    enc.bmi, 
    enc.contact_date, 
    enc‌​.[weight], 
    enc.height,
    pat.PAT_ID

4 个答案:

答案 0 :(得分:0)

试试这个:

SELECT * FROM dbo.bloodpressures WHERE YEAR(Date) = 2015

答案 1 :(得分:0)

并详细说明gabrielVas的答案,因为你特意询问了最后一个值

SELECT * FROM dbo.bloodpressures WHERE YEAR(Date) = 2015
order by date desc
limit 1

答案 2 :(得分:0)

您遇到的问题是您只获取绝对最大日期,因为:

select pat_id, max(contact_date) as LastEncounter
....
enc2.pat_id and enc.contact_date = enc2.lastencounter

where子句仅在匹配后限制数据。

要获取2015年的数据,您还需要获得2015年的最长日期:

inner join (
    select pat_id, max(contact_date) as LastEncounter 
    from pat_enc 
    where contact_date < '2016-01-01' 
    group by pat_id
    ) enc2 on enc.pat_id = enc2.pat_id and enc.contact_date = 

答案 3 :(得分:0)

您只需应用MAX

,而不是ROW_NUMBER子查询
select
    pat.pat_last_name, 
    pat.pat_first_name, 
    pat.birth_date, 
    enc.bmi, 
    enc.contact_date, 
    enc.[weight], 
    enc.height, 
    pat.PAT_ID 
from 
    patient as pat 
    inner join
      (
        select *,
            row_number() 
            over (partition by pat_id 
                  order by contact_date desc) as rn 
        from pat_enc 
        where contact_date < '2016-01-01'
          and bmi is not null -- depending on your need might be moved to the outer WHERE
      ) as enc 
    on enc.pat_id = pat.pat_id 
where rn = 1 

顺便说一句,GROUP BYDISTINCT完全相同,如果patient.pat_id是唯一的,则不需要它。