2016-07-08 37 views
0

加入最接近的值我有一个如下表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(没有任何较低日期)。

这可能吗?

+0

在每个新的原始日期都会增加吗?我的意思是日期不是随机的吗? –

+0

“但't2.date'必须最接近't1.date'(不是更低的日期)。”你的意思是从't2'最接近't1.date'的日期,但也是't1之后的日期。日期“,对吧? –

+0

@FathahRehmanP日期是随机的,没有严格增加 –

回答

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切片中的前一行号的那个行。

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;