[英]How do you join tables so that right table values depend on two different rows in left table
Sorry for messy title, if you are a moderator and know a better title, feel free to change.抱歉标题凌乱,如果您是版主并且知道更好的标题,请随时更改。
Say, we have two SQL tables说,我们有两个 SQL 表
intervals vals -------- ------- since val -------- ------- 1 1 4 2 8 3 20 4 ... ... 500 100
I want to make a join so that "since" field from intervals table would be a lower bound for a "val".我想进行连接,以便间隔表中的“since”字段成为“val”的下限。 And "since" values that have no "val" that is larger would not appear.并且不会出现没有更大“val”的“since”值。 See what I want to get:看看我想得到什么:
since val -------------- 1 1 1 2 1 3 4 4 4 5 4 6 4 7 8 8 8 9 .....
How do I do it in generic SQL?如何在通用 SQL 中做到这一点? Postgres-only solution will fit as well.仅限 Postgres 的解决方案也适用。
Rather than think of it as "multiple rows", think of it as a range .与其将其视为“多行”,不如将其视为一个范围。
This does what you want:这可以满足您的要求:
select i.since, v.val
from intervals i
join vals v on v.val between i.since and
(select min(since) - 1 from intervals where since > i.since)
order by 1, 2;
Test code (run on postgres as per OP's question):测试代码(根据 OP 的问题在 postgres 上运行):
create table intervals (since int);
create table vals (val int);
insert into intervals values (1), (4), (8), (20), (500);
insert into vals values (1), (2), (3), (4), (5), (6), (7), (8), (9), (100);
Output from above query: Output 来自上述查询:
1 1
1 2
1 3
4 4
4 5
4 6
4 7
8 8
8 9
20 100
Credit to RhodiumToad on #postgresql归功于 #postgresql 上的 RhodiumToad
SELECT *
FROM vals v
JOIN (select since
, lead(since) over (order by since) as "end"
from intervals) s
ON ( v.val >= s.since
AND ((v.val >= s."end") IS NOT TRUE)
)
;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.