SQL获取与max()关联的列值

SQL获取与max()关联的列值,sql,Sql,我有下表 ID Version --- ---------- 123 1 124 2 125 3 126 4 127 5 128 6 现在我需要在version#最大的位置获取ID值 我能做的就是 select ID from tbl where version = (selec

我有下表

ID     Version         
---    ----------    
123      1           
124      2           
125      3           
126      4           
127      5           
128      6    
现在我需要在version#最大的位置获取ID值

我能做的就是

select ID from tbl where version = (select max(version) from tbl)
我不想使用它,因为我需要在另一个查询的连接中使用这个部分,我不想让事情进一步复杂化

您可以使用选择:

或使用“限制1”选项限制结果数:

您可以使用选择:

或使用“限制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)

您提到在连接中需要它,所以类似这样的东西应该可以做到这一点

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)

这两种都不是标准SQL,OP也没有指定数据库。(编辑:事实上,我不知道什么是SQL标准的一部分,但更相关的是,我知道有一些广泛使用的数据库引擎不支持这两个方面。)@hvd你是对的,但OP应该提到DBMS是它的相关部分,我猜一旦它对他不起作用,他将不得不这样做。这两个都不是标准SQL,OP没有指定数据库。(编辑:事实上,我不知道什么是SQL标准的一部分,但更相关的是,我知道有一些广泛使用的数据库引擎不支持这两个方面。)@hvd你是对的,但OP应该提到DBMS是它的相关部分,我猜一旦它对他不起作用,他就必须这样做。
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