![](/img/trans.png)
[英]How to get Max of sum of two columns, with associated column - SQL Live
[英]SQL get column value associated with max()
我有下表
ID Version
--- ----------
123 1
124 2
125 3
126 4
127 5
128 6
现在我需要获取版本号最大的ID值
我能做的是
select ID from tbl where version = (select max(version) from tbl)
我不想使用它,因为我需要在另一个查询中的联接中使用这一部分,并且我不想进一步使事情复杂化。
您可以使用select FIRST() :
SELECT FIRST(id) FROM tbl ORDER BY Version DESC
或使用LIMIT 1选项限制结果数:
SELECT id FROM tbl ORDER BY Version DESC LIMIT 1
您提到在联接中需要此功能,因此应执行以下操作
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
(这是ANSI SQL,因为您没有提到DBMS-但应该在大多数现代DBMS上都可以使用)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.