【问题标题】:Subquery to pull single record by Max DateTime Field通过 Max DateTime 字段提取单个记录的子查询
【发布时间】:2017-04-10 16:13:55
【问题描述】:

我有一个子查询 (MS SQL 2016) 来提取特定度量的最新度量值。我需要通过 PAT_ID 将结果度量值链接回我的主查询。我遇到的问题是我无法让 MAX Date(最近的日期)在子查询中只提取一条记录。

以下查询返回大量记录,而不仅仅是最近的记录

    SELECT distinct meas.MEAS_VALUE, rec.pat_id, MAX(meas.ENTRY_TIME) "MAX ET"
    from ip_flwsht_rec rec
        inner join [CLARITY].[dbo].[IP_FLWSHT_MEAS] meas on rec.fsd_id=meas.FSD_ID 
            and meas.flo_meas_id='14' 
            and meas.MEAS_VALUE is not null
    where meas.ENTRY_TIME>=(DATEADD(day, DATEDIFF(day, 0,getdate()) - 548, 0))
        AND rec.pat_id = 'CENSORED'
    GROUP BY meas.MEAS_VALUE, rec.PAT_ID 

这会返回结果...

同一位患者有 9 个结果,但我只想要最近的。不知道我做错了什么,非常感谢任何帮助。

【问题讨论】:

  • 您的查询让我感到困惑,因为您选择的是MEAS_VALUE,但两个表之间的连接涉及FSD_ID 列。

标签: sql sql-server


【解决方案1】:

根据您的要求,@Zack 的答案中的top 1 方法可能是最好的方法。它具有所有品质中最具救赎性的特点之一,即简单。

如果top 1 方法不能满足您的要求,那么您非常接近。在你的问题中,你说,I need to link the resulted measure value back to my main query by PAT_ID。实际上,您需要将其与 pat_id 和 entry_time 两个字段链接起来。

为确保您只为每位患者获取一份记录,请更改以下内容:

SELECT distinct meas.MEAS_VALUE, rec.pat_id, MAX(meas.ENTRY_TIME) "MAX ET"

到这里:

SELECT rec.pat_id, MAX(meas.ENTRY_TIME) "MAX ET"

您的最终查询类似于以下内容:

with mostRecentRecords as (
select rec.pat_id, MAX(meas.ENTRY_TIME) mostRecentEntry
from etc
group by rec.pat_id
)
select whatever
from your tables
join mostRecentRecords on rec.pat_id = mostRecentRecords.pat_id
     and meas.entry_time = mostRecentEntry

【讨论】:

  • 丹 - 这正是我所需要的! “TOP 1”将满足测试个别患者的需求,但不适用于所有患者。正如您所指出的,我在没有加入两个字段(时间和 Pat_id)的情况下获得了额外的行。非常感谢!!!
【解决方案2】:

只需在您的选择中添加 TOP(1),然后按时间排序:

SELECT distinct TOP(1) meas.MEAS_VALUE, ...
...
ORDER BY meas.ENTRY_TIME DESC

【讨论】:

  • 这可行,但我需要在我的主查询中获取所有患者的最高值,而不是我正在测试的特定 PAT_ID。
  • 好吧,那不一样了。在您的问题中,您暗示您得到的 9 个答案是正确的,而您只需要最上面的一个。您应该使用更多详细信息更新您的问题。
【解决方案3】:

在加入之前使用row_number()meas 记录进行排序,并按fsd_id 进行分区。无需 group by 或聚合,即可为每个 fds_id 生成来自 meas 的最新记录。

select
    meas.MEAS_VALUE
  , rec.pat_id
  , [Max ET] = meas.ENTRY_TIME
from ip_flwsht_rec rec
  inner join (
    select *
      , rn = row_number() over (partition by fsd_id order by ENTRY_TIME desc)
    from [CLARITY].[dbo].[IP_FLWSHT_MEAS]
    ) as meas 
        on rec.fsd_id=meas.FSD_ID 
       and meas.rn = 1 /* just the latest row based on `entry_time` */
       and meas.flo_meas_id='14' 
       and meas.MEAS_VALUE is not null
where meas.ENTRY_TIME>=(dateadd(day, datediff(day, 0,getdate()) - 548, 0))
    and rec.pat_id = 'CENSORED'

【讨论】:

  • 你不想错过where rn = 1 吗?
  • @JuanCarlosOropeza 它在加入中
  • 我试过这个,运行了两分钟,更何况它返回了错误的结果。它似乎给了我最小的测量值,而不是链接到最大日期条目的值。
猜你喜欢
  • 2023-03-21
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 2022-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多