3

我在 PostgreSQL 中有一个带有一个数字列的表,并且我有一个给定的数字x

如果x在表中,我想要所有数字>= x

如果x不在表中,我想要所有数字> x和最大的数字< x

例子:

id 
5
10
15
20

因为x = 15它应该返回15and 20

因为x = 12它应该返回10,1520

我尝试了以下方法:

SELECT id FROM table_name WHERE id > 12
UNION
SELECT MAX(id) FROM table_name WHERE id <= 12

哪个工作正常。

有没有单查询方式?谢谢你。

(这只是一个单列和数字的例子。实际是更大的表和日期时间列,但原理应该是一样的。)

4

3 回答 3

4

从我的评论转换:

SELECT id 
  FROM table_name 
 WHERE id >= (SELECT MAX(id) 
                FROM table_name 
               WHERE id <= 12)
于 2012-07-18T12:51:26.097 回答
2
select * from A where id >= coalesce((select id from A where id = 13),(select id from A where id < 13 order by id desc limit 1));

select * from A where id >= coalesce((select id from A where id = 15),(select id from A where id < 15 order by id desc limit 1));
于 2012-07-18T13:11:44.323 回答
0

还有另一种使用windows函数的方法:

select id
from (select id, lead(id) over (order by id) as nextid
      from t
     ) t
where nextid >= 12
于 2012-07-18T13:06:15.780 回答