[英]SQL get column value associated with max()
I have the following table 我有下表
ID Version
--- ----------
123 1
124 2
125 3
126 4
127 5
128 6
Now I need to get ID value where version# is maximum 现在我需要获取版本号最大的ID值
What I can do is 我能做的是
select ID from tbl where version = (select max(version) from tbl)
I don't want to use this since i need to use this part in a join inside another query and i don't want to complicate things further. 我不想使用它,因为我需要在另一个查询中的联接中使用这一部分,并且我不想进一步使事情复杂化。
You mentioned you need this in a join, so something like this should do it 您提到在联接中需要此功能,因此应执行以下操作
select *
from table_1 as t1
join (
select id,
row_number() over (order by version desc) as rn
from table_2
) as t2 on t1.id = t2.id and t2.rn = 1
(This is ANSI SQL as you didn't mention a DBMS - but should work on most modern DBMS) (这是ANSI SQL,因为您没有提到DBMS-但应该在大多数现代DBMS上都可以使用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.