繁体   English   中英

独特的配对,其中每个值在任一侧仅出现一次

[英]Unique pairing where each value appears only once on either side

我有这张表,有两列 p1,p2。 我想要一个最大数量的组合,并限制在 output 中不能出现多次。 p1 - p2 与 p2 - p1 相同

a - b
a - c
b - c
a - d
e - d
b - d
c - d
e - f
d - f
a - g
e - g
b - g
c - g
d - g
f - g

预期结果:

f - g
d - c
b - a
e nomatchup

这是我在一个简单的临时表中使用的数据。

select * 
into #temptable
from (
select 'a' p1,'b' p2 union all
select 'a','c' union all
select 'b','c' union all
select 'a','d' union all
select 'e','d' union all
select 'b','d' union all
select 'c','d' union all
select 'e','f' union all
select 'd','f' union all
select 'a','g' union all
select 'e','g' union all
select 'b','g' union all
select 'c','g' union all
select 'd','g' union all
select 'f','g' 
) z

把它想象成需要分配到第一轮淘汰赛的不同球员,每个球员在第一轮只能上场一次。 但由于可用性,并非所有组合都是可能的。 这将是第一天比赛的查询,谁在第一轮没有得到比赛将被放入第二天比赛的池中。 所以在第一天有几个没有比赛的球员没什么大不了的,但我试图在第一天最大限度地增加比赛的数量。

我想我需要做一些事情,比如连接 p1 p2 列并以某种方式使其等同于 p2 p1 然后 select 与那里不同,然后再次将它们分开。

您可以使用连接获得匹配对。 这会生成所有这些:

select concat(t1.p1, ':', t1.p2),
       concat(t2.p1, ':', t2.p2),
       concat(t3.p1, ':', t3.p2)
from t t1 join
     t t2
     on t2.p1 not in (t1.p1, t1.p2) and
        t2.p2 not in (t1.p1, t1.p2) join
     t t3
     on t3.p1 not in (t1.p1, t1.p2, t2.p1, t2.p2) and
        t3.p2 not in (t1.p1, t1.p2, t2.p1, t2.p2);

您可以使用select top (1)返回任意单行。

是一个 db<>fiddle。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM