sql - 如何从重复的行号中找到最小值?
问题描述
我需要找到“LastUpdatedAt”的最小日期值,但只能在相同的 rowId 之间
我制作了一个临时表“#results”以包含“rowId”和“LastUpdatedAt”字段。我需要找到 RowId 的最短日期。例如,如果有两个带有 rowId '9' 的条目,我必须找到最先发生的 LastUpdatedAt。我尝试使用 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 的最短日期?
解决方案
你想要一个相关子句:
update MemberCarrierMap
set CreatedAt = (select MIN(LastUpdatedAt) from #results r where r.rowId = MemberCarrierMap.rowId)
Where CreatedAt is null;
推荐阅读
- flutter - 在 Flutter 中保留状态的引用是否安全?
- c - Boehm GC 是否将 Win32 Fibers 堆栈识别为根?
- reactjs - 为什么蚂蚁设计抽屉不显示关闭图标?
- python - 构建节点链?
- rust - 使用数组类型加载 yaml 配置
- python - 如何根据 Python 中的 predict_proba 计算相等的错误率?
- wordpress - 如何使用 woocommerce rest api 和 paypal 创建支付网关?
- javascript - 在 Vue + Vuetify 中使用 SnackBar 作为全局组件
- excel - 为什么 ActiveChart.SetSourceData 拒绝选择?
- python - pygame - 黑屏