Postgres:如何从相同的 table 中加入最接近的值

Postgres: how to join closest value from the same table

我有以下table

CREATE TABLE temp (
    id SERIAL,
    other_id INTEGER NOT NULL, -- some ForeignKey
    date DATE NOT NULL
)

我想通过具有相同 other_id 的前一个(最接近的)date 项将此 table 加入自身。像

SELECT count(*) 
FROM temp AS t1
JOIN temp AS t2 ON (t2.other_id = t1.other_id AND t2.date < t1.date) 

但是 t2.date 必须最接近 t1.date(不是任何更小的日期)。

这可能吗?

目前还不完全清楚你在追求什么,但像这样的事情可能会做到:

select count(*)
from temp as t1
  join lateral (
      select t.other_id, max(t.date)
      from temp as t 
      where t.date < t1.date
        and t.other_id = t1.other_id
      group by t2.other_id
  ) as t2 on t2.other_id = t1.other_id;

您可以使用如下查询:

WITH temp_rn AS (
  SELECT id, other_id, date,
         ROW_NUMBER() OVER (PARTITION BY other_id 
                            ORDER BY date) AS rn
  FROM temp
)
SELECT t1.*
FROM temp_rn AS t1
LEFT JOIN temp_rn AS t2 ON t1.other_id = t2.other_id AND t1.rn = t2.rn + 1

查询使用 ROW_NUMBER 来检测 'previous' 行:它是在同一 other_id 切片中具有前一个行号的行。