我正在使用PostgreSQL 9.5 我有一张这样的桌子:
CREATE TABLE tracks (
track bigserial NOT NULL,
time_track timestamp,
CONSTRAINT pk_aircraft_tracks PRIMARY KEY ( track )
);
我想通过SELECT运算符获取最接近datetime值的轨道。 例如,如果我有:
track datatime
1 | 2016-12-01 21:02:47
2 | 2016-11-01 21:02:47
3 |2016-12-01 22:02:47
对于输入数据时间2016-12-01 21:00,曲目为2。
我对Is there a postgres CLOSEST operator?类似的整数问题进行了调查。 但它不适用于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 :(得分: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)