Postgres的:如何从同一个表
问题描述:
加入最接近的值我有一个如下表Postgres的:如何从同一个表
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
(没有任何较低日期)。
这可能吗?
答
您可以使用查询类似如下:
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
切片中的前一行号的那个行。
答
这不是完全清楚你所追求的,但这样的事情可能做到这一点:
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;
在每个新的原始日期都会增加吗?我的意思是日期不是随机的吗? –
“但't2.date'必须最接近't1.date'(不是更低的日期)。”你的意思是从't2'最接近't1.date'的日期,但也是't1之后的日期。日期“,对吧? –
@FathahRehmanP日期是随机的,没有严格增加 –