我有下表
CREATE TABLE temp (
id SERIAL,
other_id INTEGER NOT NULL, -- some ForeignKey
date DATE NOT NULL
)
我希望通过具有相同date
的上一个(最近的)other_id
项将此表连接到自身。像
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
(不是更低的日期)。
这可能吗?
答案 0 :(得分:2)
您可以使用如下查询:
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
来检测“上一个”行:它是在同一个other_id
切片中具有前一个行号的行。
答案 1 :(得分:0)
你所追求的并不完全清楚,但是这样的事情可能会这样做:
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;