【问题标题】:Closest datetime for PostgreSQL 9.5PostgreSQL 9.5 的最近日期时间
【发布时间】:2016-12-03 15:54:35
【问题描述】:

我使用的是 PostgreSQL 9.5 我有一张这样的桌子:

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

我想通过 SELECT 运算符获取最接近的日期时间值。 例如,如果我有:

  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? 类似的整数问题。 但它不适用于数据时间或 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

【问题讨论】:

  • AS aboveAS below 是多余的。

标签: postgresql datetime


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 2013-08-01
    • 1970-01-01
    • 2010-10-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多