postgresql WHERE timea = timeb,如何指定精度?

时间:2016-07-28 14:54:45

标签: sql postgresql datetime postgresql-9.3

我正在做一些与不同表格的时间序列数据匹配的工作。 作为示例,该表具有1秒时间序列的列和最近的小时'列如:

"datetime"                  "closesthourdatetime"
"01/01/2005 00:30:00"       "01/01/2005 01:00:00"
"01/01/2005 00:30:01"       "01/01/2005 01:00:00"
"01/01/2005 00:30:02"       "01/01/2005 01:00:00"

如果我跑

    SELECT time_series_only.closesthourdatetime
    FROM measdata.time_series_only
    WHERE time_series_only.datetime = time_series_only.closesthourdatetime

与运行

不同,我没有得到我所希望的所有结果
  SELECT DISTINCT time_series_only.closesthourdatetime
  FROM measdata.time_series_only
我在哪里。

我猜测这是因为pgsql日期时间实际上是数字值,时间是一天的一部分,所以毫秒可能不完全匹配,我并不关心。

有没有办法查询,但指定最近的秒或分钟     WHERE time_series_only.datetime = time_series_only.closesthourdatetime 没有像这样的复杂且可能很慢的查询? :

  SELECT DISTINCT time_series_only.closesthourdatetime
  FROM measdata.time_series_only
  --WHERE 
  --time_series_only.datetime = time_series_only.closesthourdatetime
  /*EXTRACT (YEAR FROM time_series_only.datetime)   = EXTRACT(YEAR FROM time_series_only.closesthourdatetime)
  AND EXTRACT (MONTH FROM time_series_only.datetime)    = EXTRACT(MONTH FROM time_series_only.closesthourdatetime)
  AND EXTRACT (DAY FROM time_series_only.datetime)  = EXTRACT(DAY FROM time_series_only.closesthourdatetime)
  AND EXTRACT (HOUR FROM time_series_only.datetime)     = EXTRACT(HOUR FROM time_series_only.closesthourdatetime)
  AND EXTRACT (MINUTE FROM time_series_only.datetime) = EXTRACT(MINUTE FROM time_series_only.closesthourdatetime)
  AND EXTRACT (SECOND FROM time_series_only.datetime) = EXTRACT(SECOND FROM time_series_only.closesthourdatetime)

1 个答案:

答案 0 :(得分:2)

您可以使用以下where子句获得预期结果:

WHERE datetime >= closesthourdatetime - INTERVAL '30 MINUTE'
AND   datetime <  closesthourdatetime + INTERVAL '30 MINUTE'

此处,latesthourdatetime 01/01/2005 01:00:00将匹配[01/01/2005 00:30:00, 01/01/2005 01:30:00)范围内所有日期时间,其中第二个日期是独占的。

SQL Fiddle for test/edge cases