gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:49:36 25 4
gpt4 key购买 nike

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

我尝试过涉及 ROW_NUMBER() 的解决方案和 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

当前结果:
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

需要的结果:
ID  Color   ID  Color
--- ------- --- --------
1 Blue 3 Blue
2 Red 6 Red

最佳答案

用最大评论编辑

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

我首先根据 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

我得到如下输出
+----+-------+----+-------+
| id | color | id | color |
+----+-------+----+-------+
| 1 | Blue | 3 | Blue |
| 5 | Blue | 7 | Blue |
| 2 | Red | 6 | Red |
+----+-------+----+-------+

关于sql - 在 SQL Server 中仅使用一次记录查找匹配对,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60621262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com