[英]SQL Server: join two tables where left table contains all rows of right table in each of its identifier
[英]How do you join tables so that right table values depend on two different rows in left table
抱歉標題凌亂,如果您是版主並且知道更好的標題,請隨時更改。
說,我們有兩個 SQL 表
intervals vals -------- ------- since val -------- ------- 1 1 4 2 8 3 20 4 ... ... 500 100
我想進行連接,以便間隔表中的“since”字段成為“val”的下限。 並且不會出現沒有更大“val”的“since”值。 看看我想得到什么:
since val -------------- 1 1 1 2 1 3 4 4 4 5 4 6 4 7 8 8 8 9 .....
如何在通用 SQL 中做到這一點? 僅限 Postgres 的解決方案也適用。
與其將其視為“多行”,不如將其視為一個范圍。
這可以滿足您的要求:
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);
Output 來自上述查詢:
1 1
1 2
1 3
4 4
4 5
4 6
4 7
8 8
8 9
20 100
歸功於 #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.