3

PostgreSQLに1つの数値列を持つテーブルがあり、指定された数値がありxます。

がテーブルにある場合xは、すべての番号が必要です>= x

xが表にない場合は、すべての番号> xと最大の番号が必要< xです。

例:

id 
5
10
15
20

それx = 15は戻ってくるはず15です20

、、x = 12を返す必要1015あり20ます。

私は以下を試しました:

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 に答える