如何从 T-SQL table 中提取最新值

How to pull the most recent values from a T-SQL table

我有一个数据库 table,我需要使用视图或存储过程或其他可以根据实时数据给我结果的东西来处理它。

table 保存了人的记录以及与每个人相关的数据。问题是人们可以不止一次出现在 table 中。每条记录显示一个人的一条或多条信息被记录的时间。

人员的标识符字段是 cardholder_index。我需要获取该字段的 DISTINCT 列表。还有一个名为 bio_complete_date 的日期字段。我需要做的是,对于 table 中的所有其他字段,取最近的非空(或可能非零)值。

比如有一个bmi字段。对于每个不同的持卡人索引,我需要为那个 cardholder_index 获取最近的(通过 bio_complete_date 字段)非空 bmi。但是还有一个 body_fat 字段,我需要在该字段中取最近的非空值,它可能不一定与最近的非空 bmi 值在同一行。

郑重声明,table 本身确实有自己的唯一标识符列 bio_id,如果有帮助的话。

我不需要显示何时 获取了最新的一条信息。我只需要显示数据本身。

我想我需要在 card_holder 索引上做一个 distinct,然后将每个其他字段的查询结果集连接到它。它正在编写给我带来问题的子查询。

根据你的描述,我猜你的 table 看起来像这样:

create table people (
    bio_id int identity(1,1), 
    cardholder_index int, 
    bio_complete_date date, 
    bmi int, 
    body_fat int
)

如果是这样,进行查询的一种(许多)方法是使用相关查询来提取 cardholder_index 的最新非空值,或者使用像这样的子查询:

select 
    cardholder_index, 
    (
       select top 1 bmi 
       from people 
       where cardholder_index = p.cardholder_index and bmi is not null 
       order by bio_complete_date desc
    ) as latest_bmi, 
    (
       select top 1 body_fat 
       from people 
       where cardholder_index = p.cardholder_index and body_fat is not null 
       order by bio_complete_date desc
    ) as latest_body_fat
from people p
group by cardholder_index

或者像这样使用 apply 运算符:

select cardholder_index, latest_bmi.bmi, latest_body_fat.body_fat
from people p
outer apply (
    select top 1 bmi 
    from people 
    where cardholder_index = p.cardholder_index and bmi is not null 
    order by bio_complete_date desc
) as latest_bmi
outer apply (
    select top 1 body_fat 
    from people 
    where cardholder_index = p.cardholder_index and body_fat is not null 
    order by bio_complete_date desc
) as latest_body_fat
group by cardholder_index, latest_bmi.bmi, latest_body_fat.body_fat

Sample SQL Fiddle demo