2013-07-03 66 views
0

我在離散時間點有一組位置。我想使用一個函數,它將返回第一個更小的時間戳和第一個更高的時間戳的位置。PostgreSQL查找周邊值

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) 

回答

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

是的,你可以將它們'聯合'在一起作爲子查詢來獲得單個邏輯查詢的結果。並不是說它會造成很大的差別。 –

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))