我想用SQL(No PL / SQL!或其他东西)选择最接近的值小于给定值的条目。
我到目前为止:
select max(RUN_ID) from RUN_TABLE where KEY = 'TEST#33' and RUN_ID < 3
这将返回与键匹配的最小值小于3的行,但我希望能够选择所有列。
Run_ID Entity Key
1 HK TEST#11
2 AB TEST#22
2 CK TEST#33
3 TB TEST#22
3 DB TEST#33
我希望能够使用密钥TEST#22和最大RUN_ID 4来选择行:
3 TB TEST#22
当说最大RUN_ID 2要检索
时2 AB TEST#22
答案 0 :(得分:2)
按运行ID降序排序,仅取第一行,对于Oracle:
select top 1 * from RUN_TABLE
where KEY = 'TEST#33' and RUN_ID < 3
order by RUN_ID desc
fetch first 1 rows
或SQL Server(因为SQLFiddle的Oracle选项已关闭):
select top 1 * from RUN_TABLE
where KEY = 'TEST#33' and RUN_ID < 3
order by RUN_ID desc
答案 1 :(得分:0)
select Run_ID, Entity, Key from from RUN_TABLE a
where Run_ID = (select max(RUN_ID) from RUN_TABLE b where b.Key = a.Key and RUN_ID < 3)
and KEY = 'TEST#33'
答案 2 :(得分:0)
类似的东西:
select t1.*
from RUN_TABLE t1
join (
select max(RUN_ID) AS MAX_RUN_ID
from RUN_TABLE
where KEY = 'TEST#33' and RUN_ID < 3
) t2 ON t1.RUN_ID = t2.MAX_RUN_ID
WHERE KEY = 'TEST#33'