小编Car*_*eum的帖子

在 SQL Server 中仅使用一次记录查找匹配对

我需要在 SQL Server 中找到匹配的记录对,但每条记录只能包含在1 pair 中。一旦记录与一对匹配,就应该将其从任何未来对的考虑中删除。

我已经尝试过涉及ROW_NUMBER()and 的解决方案LEAD(),但我无法完全到达那里。

这将用于根据信用评分、收入等多个客户属性,将金融账户与类似账户配对进行审查。

陈述:

declare @test table (ID numeric, Color varchar(20))
insert into @test values
        (1,'Blue'),(2,'Red'),(3,'Blue'),(4,'Yellow'),(5,'Blue'),(6,'Red')

select* 
from @test t1
join @test t2 
    on t1.Color = t2.Color
    and t1.ID < t2.ID           -----removes reverse-pairs and self-pairs
Run Code Online (Sandbox Code Playgroud)

当前结果:

ID  Color   ID  Color
--- ------- --- --------
1   Blue    3   Blue
1   Blue    5   Blue        -----should not appear because 1 has already been paired
3   Blue    5   Blue        -----should not appear …
Run Code Online (Sandbox Code Playgroud)

sql t-sql sql-server pairwise

5
推荐指数
1
解决办法
162
查看次数

标签 统计

pairwise ×1

sql ×1

sql-server ×1

t-sql ×1