如何根据不同列的值检索最大ID

时间:2018-06-16 17:13:24

标签: sql sql-server

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

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

数据集:

+----+-------------+--------------+
| 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 |  
+----+-------------+--------------+--------------+

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

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

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