一系列日期的最接近记录

roo*_*oot 5 sql postgresql datetime

我知道要在日期之前获得最接近的记录,我可以使用查询:

select * 
from results 
where resulttime = (select max(resulttime) 
                    from results 
                    where some_id = 15 
                      and resulttime < '2012-07-27');
Run Code Online (Sandbox Code Playgroud)

但我需要这样做一段时间,以便我知道每天最接近的记录.有任何想法吗?

这一系列的日子将由generate_sequence().

最接近的先前记录可能是我们想要的值的前一天,但仍需要返回.

Erw*_*ter 4

LEFT JOIN使用and应该是最简单且最快的DISTINCT ON

WITH x(search_ts) AS (
    VALUES
     ('2012-07-26 20:31:29'::timestamp)              -- search timestamps
    ,('2012-05-14 19:38:21')
    ,('2012-05-13 22:24:10')
    )
SELECT DISTINCT ON (x.search_ts)
       x.search_ts, r.id, r.resulttime
FROM   x
LEFT   JOIN results r ON r.resulttime <= x.search_ts -- smaller or same
-- WHERE some_id = 15                                -- some condition?
ORDER  BY x.search_ts, r.resulttime DESC;
Run Code Online (Sandbox Code Playgroud)

结果(虚拟值):

search_ts           | id     | resulttime
--------------------+--------+----------------
2012-05-13 22:24:10 | 404643 | 2012-05-13 22:24:10
2012-05-14 19:38:21 | 404643 | 2012-05-13 22:24:10
2012-07-26 20:31:29 | 219822 | 2012-07-25 19:47:44
Run Code Online (Sandbox Code Playgroud)

我使用CTE来提供值,可以是表、函数、非嵌套数组,也可以是用generate_series()其他东西生成的集合。(您的意思generate_series()是“generate_sequence()”吗?)

首先,我JOIN对表中所有具有 before 或 equal 的行进行搜索时间戳resulttime。我使用LEFT JOIN而不是这样,当表中根本JOIN没有先验信息时,搜索时间戳就不会被删除。resulttime

DISTINCT ON (x.search_ts)结合,我们得到小于或等于每个搜索时间戳的ORDER BY x.search_ts, r.resulttime DESC最大(或同等最大之一) 。resulttime