单独考虑每个值 A/B/AA,并使用窗口函数查找 col3 和 col4 上的滞后超前
将每个“prev_col3、col3、next_col3、prev_col4、col4、next_col4”视为唯一的“上下文”标识符并加入。这就是我们可以避免混淆数据中的第 7 行和第 9 行的方法;对于 col3 和 col4,它们具有不同的 prev/next 滞后/领先值。
我们需要控制 null 情况(我将 null 设置为 -1)以使连接起作用。
您可以将其复制/粘贴到 SQL Server 中以查看它的工作原理:
CREATE TABLE #TABLE1 (col1 INT, col2 varchar(5), col3 INT, col4 INT)
CREATE TABLE #TABLE2 (col1 INT, col2 INT, col3 INT)
INSERT INTO #TABLE1
select 1 col1,'A' col2, 1 col3, 1 col4 union
select 2 col1,'A' col2, 1 col3, 2 col4 union
select 5 col1,'A' col2, 1 col3, 1 col4 union
select 6 col1,'B' col2, 2 col3, 1 col4 union
select 7 col1,'AA' col2, 1 col3, 1 col4 union
select 8 col1,'AA' col2, 1 col3, 2 col4 union
select 9 col1,'AA' col2, 1 col3, 1 col4
INSERT INTO #TABLE2
select 1 col1, 1 col2, 12 col3 union
select 2 col1,2 col2, 45 col3 union
select 3 col1,5 col2, 22 col3 union
select 4 col1,6 col2, 21 col3
select
Bu.col1, bu.col2, bu.col3, bu.col4, t2.col1, t2.col2, t2.col3
from
(
select
col1, col2,
lag(col3) over (order by col1 asc) prev_col3,
col3,
lead(col3) over (order by col1 asc) next_col3,
lag(col4) over (order by col1 asc) prev_col4,
col4,
lead(col4) over (order by col1 asc) next_col4
from
#TABLE1 t1 where col2 in ('A')
) A
join
( /*bu big union*/
select
col1, col2,
lag(col3) over (order by col1 asc) prev_col3,
col3,
lead(col3) over (order by col1 asc) next_col3,
lag(col4) over (order by col1 asc) prev_col4,
col4,
lead(col4) over (order by col1 asc) next_col4
from
#TABLE1 t1 where col2 in ('A')
UNION
select
col1, col2,
lag(col3) over (order by col1 asc) prev_col3,
col3,
lead(col3) over (order by col1 asc) next_col3,
lag(col4) over (order by col1 asc) prev_col4,
col4,
lead(col4) over (order by col1 asc) next_col4
from
#TABLE1 t1 where col2 in ('AA')
) bu
on
(
a.col3 = bu.col3 and isnull(a.prev_col3,-1) = isnull(bu.prev_col3,-1) and
isnull(a.next_col3,-1) = isnull(bu.next_col3,-1) and
a.col4 = bu.col4 and isnull(a.prev_col4,-1) = isnull(bu.prev_col4,-1) and
isnull(a.next_col4,-1) = isnull(bu.next_col4 ,-1)
)
join
#TABLE2 t2
on
a.col1 = t2.col2
UNION
select
t1.col1, t1.col2, t1.col3, t1.col4,
t2.col1, t2.col2, t2.col3
from
#TABLE1 t1
join #TABLE2 t2 on t1.col1 = t2.col2
where t1.col2 = 'B'
order by 1 asc
drop table #TABLE1
drop table #TABLE2