2

我想用 SQL 选择最接近的值小于给定值的条目(没有 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
4

3 回答 3

2

对于 Oracle,按运行 id 降序排列并仅取第一行:

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

在 SQLFiddle 上进行现场演示

于 2016-06-03T16:35:46.863 回答
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'
于 2016-06-03T15:37:50.840 回答
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'
于 2016-06-03T15:41:16.417 回答