2016-12-03 97 views
0

我使用PostgreSQL 9.5 和我有一個表是這樣的:最近的日期時間對PostgreSQL 9.5

CREATE TABLE tracks ( 
    track    bigserial NOT NULL, 
    time_track   timestamp, 
    CONSTRAINT pk_aircraft_tracks PRIMARY KEY (track) 
); 

我想獲得軌道由SELECT操作日期時間的最接近的值。 e.g,如果我有:

track datatime 
    1 | 2016-12-01 21:02:47 
    2 | 2016-11-01 21:02:47 
    3 |2016-12-01 22:02:47 

對於輸入DATATIME 2016年12月1日21點00分,軌道是2

我foud出去整數Is there a postgres CLOSEST operator?類似queston。 但它不與DATATIME工作或PostgreSQL 9.5:

SELECT * FROM 
(
    (SELECT time_track, track FROM tracks WHERE time_track >= now() ORDER BY time_track LIMIT 1) AS above 
    UNION ALL 
    (SELECT time_track, track FROM tracks WHERE time_track < now() ORDER BY time_track DESC LIMIT 1) AS below 
) 
ORDER BY abs(?-time_track) LIMIT 1; 

錯誤:

ERROR: syntax error at or near "UNION" 
LINE 4: UNION ALL 
+0

'AS above'和'AS以下「是多餘的。 – Abelisto

回答

1

軌道1是最接近'2016-12-01 21:00'

with tracks(track, datatime) as (
values 
    (1, '2016-12-01 21:02:47'::timestamp), 
    (2, '2016-11-01 21:02:47'), 
    (3, '2016-12-01 22:02:47') 
) 

select * 
from tracks 
order by 
    case when datatime > '2016-12-01 21:00' then datatime - '2016-12-01 21:00' 
    else '2016-12-01 21:00' - datatime end 
limit 1; 

track |  datatime  
-------+--------------------- 
    1 | 2016-12-01 21:02:47 
(1 row)