2016-01-24 92 views
1

使用Postgres 9.4,我試圖從包含數據的表中選擇一行,該表包含的數據與當前系統時間最接近,但不是之前。數據類型爲datetime,數據類型爲timestamp without time zone,數據與服務器在同一時區。表結構是:選擇最接近但不遲於現在的時間戳的行

uid |  datetime  | date | day | time | predictionft | predictioncm | highlow 
-----+---------------------+------------+-----+----------+--------------+--------------+--------- 
    1 | 2015-12-31 03:21:00 | 2015/12/31 | Thu | 03:21 AM |   5.3 |   162 | H 
    2 | 2015-12-31 09:24:00 | 2015/12/31 | Thu | 09:24 AM |   2.4 |   73 | L 
    3 | 2015-12-31 14:33:00 | 2015/12/31 | Thu | 02:33 PM |   4.4 |   134 | H 
    4 | 2015-12-31 21:04:00 | 2015/12/31 | Thu | 09:04 PM |   1.1 |   34 | L 

查詢速度不是一個擔心,因爲表中包含約1500行。

爲了清楚起見,如果當前服務器時間爲2015-12-31 14:00:00,返回的行應該是3而不是2

編輯: 該解決方案基於下面的接受的答案,就是:

select * 
from myTable 
where datetime = 
(select min(datetime) 
from myTable 
where datetime > now()); 

編輯2:澄清問題。

+0

最近的兩個向上和下降?我的意思是,如果有一個說'2015-12-31 13:59:00'的專欄會被選中? –

+1

豪爾赫 - 不,在任何情況下,查詢都應該選擇未來的行或者完全等於當前時間。 – surfearth

+1

你說''之前','不遲於'在問題中。但是在這個評論中「之後」。請糾正這個問題。 – Jasen

回答

2

總體思路如下。你可以調整它爲postgresql。

select fields 
from yourTable 
where datetimeField = 
(select min(datetimeField) 
from yourTable 
where datetimeField > current_timestamp) 
3

您也可以使用它。這會更快。但如果你有幾行,它不會有太大的區別。

select * from table1 
where datetime >= current_timestamp 
order by datetime 
limit 1 

SQLFiddle Demo

+0

謝謝,我確認這也適用。 – surfearth

1

比給出的答案的其他另一種方法是使用一個窗口函數first_value

select id, first_value(dt) over (order by dt) 
    from test 
where dt >= current_timestamp 
limit 1 

看到它在這裏工作:http://sqlfiddle.com/#!15/0031c/12