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

Car*_*eum 5 sql t-sql sql-server pairwise

我需要在 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 because 3 and 5 have already been paired
2   Red     6   Red
Run Code Online (Sandbox Code Playgroud)

需要的结果:

ID  Color   ID  Color
--- ------- --- --------
1   Blue    3   Blue
2   Red     6   Red
Run Code Online (Sandbox Code Playgroud)

Geo*_*eph 2

使用最大评论进行编辑

这是完成此操作的一种方法..

我首先根据颜色对记录进行排名,其中最低 id 的 rnk=1,下一个 id 的 rnk=2。

之后,我通过拉出 rnk=1 记录并然后使用 rnk=2 将表连接在一起。

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

;with data
  as (select row_number() over(partition by color order by id asc) as rnk
            ,color
            ,id
       from @test
       )
select a.id,a.color,b.id,b.color
 from data a
 join data b
   on a.Color=b.Color
  and b.rnk=a.rnk+1
where a.rnk%2=1
Run Code Online (Sandbox Code Playgroud)

我得到的输出如下

+----+-------+----+-------+
| id | color | id | color |
+----+-------+----+-------+
|  1 | Blue  |  3 | Blue  |
|  5 | Blue  |  7 | Blue  |
|  2 | Red   |  6 | Red   |
+----+-------+----+-------+
Run Code Online (Sandbox Code Playgroud)

  • @CarlyReum `WHERE a.RowNum % 2 = 1 AND b.RowNum = a.RowNum + 1`(并从连接中删除 `and b.rnk=2` 子句)。[小提琴](http://sqlfiddle.com/#!18/15eb5/1) (2认同)