选择数字"更大"比给定的数字

时间:2012-07-18 12:24:27

标签: sql postgresql

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

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

如果表格中没有x,我希望所有数字> x和最大数字< x

示例:

id 
5
10
15
20

对于x = 15,它应该返回1520

对于x = 12,它应该返回101520

我尝试了以下内容:

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

正常工作。

有任何单一查询方式吗?谢谢。

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

3 个答案:

答案 0 :(得分:4)

从我的评论转换而来:

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

答案 1 :(得分: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));

答案 2 :(得分:0)

还有另一种使用Windows功能的方法:

select id
from (select id, lead(id) over (order by id) as nextid
      from t
     ) t
where nextid >= 12
相关问题