首页 > 解决方案 > 如何从重复的行号中找到最小值?

问题描述

我需要找到“LastUpdatedAt”的最小日期值,但只能在相同的 rowId 之间

我制作了一个临时表“#results”以包含“rowId”和“LastUpdatedAt”字段。我需要找到 RowId 的最短日期。例如,如果有两个带有 rowId '9' 的条目,我必须找到最先发生的 La​​stUpdatedAt。我尝试使用 MIN(LastUpdatedAt) 但只返回整个表的最小日期。

create table #results(
    RowId       id_t,
    LastUpdatedAt date_T
)


insert into #results
select H.RowId, H.LastUpdatedAt from MemberCarrierMap M Join MemberCarrierMapHistory H on M.RowId = H.RowId

select * from #results


RowId   LastUpdatedAt

9       2010-01-21 17:07:48.640
9       2018-05-14 13:33:04.313
88      2016-11-22 14:49:13.770

update MemberCarrierMap 
set CreatedAt = (select MIN(LastUpdatedAt) from #results)
Where CreatedAt is null

我试过这个,但它只找到整个表的最小值。有没有办法只找到一个 rowID 的最短日期?

标签: sqlsql-server

解决方案


你想要一个相关子句:

update MemberCarrierMap 
set CreatedAt = (select MIN(LastUpdatedAt) from #results r where r.rowId = MemberCarrierMap.rowId)
Where CreatedAt is null;

推荐阅读