简体   繁体   English

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

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

I have this table with two columns p1, p2.我有这张表,有两列 p1,p2。 I would like a maximum number of combination with the restriction that no value should appear more than once in the output.我想要一个最大数量的组合,并限制在 output 中不能出现多次。 p1 - p2 is the same as p2 - p1 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

Expected result:预期结果:

f - g
d - c
b - a
e nomatchup

This is the data I'm playing with in a simple temp table.这是我在一个简单的临时表中使用的数据。

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

Think of it like distinct players that need to be allocated to a first round eliminatory tournament and each player gets to play only once in the first round.把它想象成需要分配到第一轮淘汰赛的不同球员,每个球员在第一轮只能上场一次。 But because of availability not all combinations are possible.但由于可用性,并非所有组合都是可能的。 This will be the query for the first day matchups, whoever doesn't get a matchup in the first round will be put in the pool for second day matches.这将是第一天比赛的查询,谁在第一轮没有得到比赛将被放入第二天比赛的池中。 So having a few players with no matchups in the first day is no big deal but I'm trying to maximize the amout of games in day 1 none the less.所以在第一天有几个没有比赛的球员没什么大不了的,但我试图在第一天最大限度地增加比赛的数量。

I'm thinking I need to do something like concaternating the p1 p2 columns and somehow make it equivalent to p2 p1 and then select distinct from there and separate them again.我想我需要做一些事情,比如连接 p1 p2 列并以某种方式使其等同于 p2 p1 然后 select 与那里不同,然后再次将它们分开。

You can get matching pairs using a join.您可以使用连接获得匹配对。 This generates all of them:这会生成所有这些:

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);

You can use select top (1) to return an arbitrary single row.您可以使用select top (1)返回任意单行。

Here is a db<>fiddle. 是一个 db<>fiddle。

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

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