首页 > 解决方案 > 查找每个值出现一次的两列的唯一组合

问题描述

我正在尝试建立一个游戏对决,其中每个玩家只玩一次并最大化游戏总数。在 15 种可能的对决中,我试图找出要选择的 p1、p2 组合。

我试过的代码:尝试1

with cte1 as(
select p1,p2,ROW_NUMBER() over(partition by p1 order by (select 0) desc) rn 
from #tempgame
) ,cte2 as (select p1,p2,ROW_NUMBER() over(partition by p2 order by (select 0) desc) rn 
from cte1
where rn=1
)select * from cte2
where rn = 1

尝试2:

    select distinct a.p2,b.p1
    from #tempgame a
    join #tempgame b
    on a.p1 = 
            ( select top 1 a.p1
            from #tempgame b
            where b.p2 = a.p2

            ) 

我什至没有设法让它满足每个玩家只玩一次的第一个条件,更不用说最大化对战的数量了。

我已经根据球员的可用性确定了只有这些比赛是可能的,并利用他们的可用性来确定比赛时间。因此,如果他们的可用时间范围不重叠,我不能只拿球员表并随机分配他们。所以问题很简单:基于简单的 p1,p2 表允许什么样的 p1,p2 组合?

select * 
INTO #tempgame
from (
select  76561197987822470 p1,76561198040907827 p2 union all 
select 76561197987822470,76561198088336999 union all
select 76561197987822470,76561198095503172 union all
select 76561197987822470,76561198397303730 union all
select 76561198001599297,76561198397303730 union all
select 76561198001599297,76561198321977951 union all
select 76561198001599297,76561198095503172 union all
select 76561198040907827,76561198088336999 union all
select 76561198040907827,76561198095503172 union all
select 76561198040907827,76561198397303730 union all
select 76561198088336999,76561198397303730 union all
select 76561198088336999,76561198095503172 union all
select 76561198095503172,76561198397303730 union all
select 76561198095503172,76561198321977951 union all
select 76561198321977951,76561198397303730 
) z

我相信只有2场比赛是可能的。我不在乎哪些。但是除了在小样本上反复试验之外,我无法找到一种合乎逻辑的计算方法。

      P1                           P2
row1 76561197987822470 vs 76561198040907827
row2 76561198001599297 vs 76561198397303730

标签: sqlsql-servermath

解决方案


我正在尝试建立一个游戏对决,其中每个玩家只玩一次并最大化游戏总数。

如果这是您的目标,请从玩家表开始并使用自联接:

select p1.player_id, p2.player_id
from players p1 join
     players p2
     on p1.player_id < p2.player_id

我不确定gametime与这个问题有什么关系——或者实际上数据或查询与它有什么关系。


推荐阅读