不好意思,如果你是版主,知道更好的标题,请随意更改。
假设我们有两个SQL表
<>之前时间间隔 瓦尔斯-------- -------自 瓦尔-------- -------1 14 28 320 4... ...500年 100年之前我想做一个连接,使"since"字段从间隔表将是一个下界的"val"。并且"since"没有更大的"val"的值将不会出现。看看我想要得到什么:
<>之前因为瓦尔--------------11 21 34个44个54 - 64个78 88 9.....之前我如何做它在通用SQL?
与其将其视为"多行",不如将其视为范围。
这是你想要的:
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;
测试代码(根据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);
上面查询的输出:
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
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)
)
;