Sql 如何根据不同列中的值检索最大id

Sql 如何根据不同列中的值检索最大id,sql,sql-server,Sql,Sql Server,假设我有3列,ID,firstcolumn,secondcolumn 我需要根据secondcolumn中的值检索firstcolumn的最大id。此返回的id必须是firstcolumn的最大id,但仍必须小于或等于每条记录的secondcolumn的值 数据集: +----+-------------+--------------+ | ID | firstcolumn | secondcolumn | +----+-------------+--------------+ | 1 |

假设我有3列,ID,firstcolumn,secondcolumn

我需要根据secondcolumn中的值检索firstcolumn的最大id。此返回的id必须是firstcolumn的最大id,但仍必须小于或等于每条记录的secondcolumn的值

数据集:

+----+-------------+--------------+
| ID | firstcolumn | secondcolumn |
+----+-------------+--------------+
|  1 |          32 |           32 |
|  1 |          32 |           35 |
|  1 |          32 |           38 |
|  1 |          34 |           32 |  
|  1 |          34 |           35 |  
|  1 |          34 |           38 |  
|  1 |          39 |           32 |  
|  1 |          39 |           35 |  
|  1 |          39 |           38 |  
|  2 |          12 |           12 |  
|  2 |          12 |           17 |  
|  2 |          18 |           12 |  
|  2 |          18 |           17 |  
+----+-------------+--------------+
结果数据集

+----+-------------+--------------+--------------+
| ID | firstcolumn | secondcolumn | resultcolumn |  
+----+-------------+--------------+--------------+
|  1 |          32 |           32 |           32 |  
|  1 |          32 |           35 |           34 |  
|  1 |          32 |           38 |           34 |  
|  1 |          34 |           32 |           32 |  
|  1 |          34 |           35 |           34 |  
|  1 |          34 |           38 |           34 |  
|  1 |          39 |           32 |           32 |  
|  1 |          39 |           35 |           34 |  
|  1 |          39 |           38 |           34 |  
|  2 |          12 |           12 |           12 |  
|  2 |          12 |           17 |           12 |  
|  2 |          18 |           12 |           12 |  
|  2 |          18 |           17 |           12 |  
+----+-------------+--------------+--------------+

任何帮助都将不胜感激

您的解释转化为相关标量子查询:

select *,
  ( select max(firstcolumn) -- maximum id of firstcolumn
    from tab as t2
    where t1.id = t2.id
      and t2.firstcolumn <= t1.secondcolumn  -- less than or equal to secondcolumn
  )
from tab as t1

嗨,欢迎来到StackOverflow。你能解释一下这个问题的目的吗?可能有更好的方法来构造数据。请标记您的DBMS,然后检查您的预期结果?这一行与您的描述不匹配:| 1 | 39 | 32 | 33 |结果应该是32?Hi@dnoeth,感谢您指出这一点。我编辑过accordingly@Schwern我会尽力解释我想做什么。此表查询项目应计资金的交易历史记录。在这个表中,我们有一个版本id,它在项目id更新时被记录。此表中的两列显示了员工secondcolumn更改时项目的版本id以及金额更新时项目的版本id firstcolumn。我需要在每次员工变动时查询,并保留每个员工变动应计金额的交易历史记录,结果列会这样做。