PostgreSQL找到周围的值

时间:2013-07-03 14:14:54

标签: sql postgresql postgresql-9.2 window-functions

我在离散时间点有一组位置。我想使用一个函数来返回第一个较小和第一个较高时间戳的位置。

E.g。

timestamp | pos
5         | (-3, -3)
10        | (0, 0)
15        | (3, 3)
20        | (6, 6)

如果我在此表中查询时间戳17,我会得到行

15        | (3, 3)
20        | (6, 6)

我期待像

这样的东西
SELECT * FROM positions WHERE timestamp = first_smaller(17)
SELECT * FROM positions WHERE timestamp = first_greater(17)

2 个答案:

答案 0 :(得分:3)

select * from positions where timestamp <= 17 order by timestamp desc limit 1;

select * from positions where timestamp >= 17 order by timestamp asc limit 1;

答案 1 :(得分:0)

这样的事情应该有效:

(SELECT * 
 FROM positions 
 WHERE timestamp = (SELECT max(timestamp) FROM position WHERE timestamp <= 17))
UNION
(SELECT * 
 FROM positions 
 WHERE timestamp = (SELECT min(timestamp) FROM position WHERE timestamp >= 17))