SQL两个表之间的所有可能的循环组合

时间:2012-11-14 02:37:27

标签: sql oracle combinations round-robin

给出表格:

create table Person( Name varchar(100) )

其中名称对所有人都是唯一的

什么SQL查询可以生成所有可能的n!/((n-2)!2!)循环组合?

假设Person的基数总是等于4

示例Person = {'Anna','Jerome','Patrick','Michael')

输出:

Anna, Jerome
Anna, Patrick
Anna, Michael
Jerome, Patrick
Jerome, Michael
Patrick, Michael

任何帮助将不胜感激。谢谢!

这是我的答案(我使用的是oracle SQL):

select P1.NAME PERSON1, P2.NAME PERSON2
  from (select rownum RNUM, NAME
        from PERSON) P1,
       (select rownum RNUM, NAME
          from PERSON) P2
 where P1.RNUM < P2.RNUM

3 个答案:

答案 0 :(得分:1)

以下是问题的两种解决方案

SELECT  t1.Name + ',' +  t2.Name AS NamesCombination
FROM Person t1
INNER JOIN Person t2
ON t1.Name < t2.Name

OR(Oracle 11i R2 +)

WITH NamesCombination AS 
( 
    SELECT  1 AS Cntr
            ,Name 
            , CAST(Name AS VARCHAR(MAX))AS NamesCombinations
    FROM Person 
    UNION ALL 
    SELECT  
        nc.Cntr+1
        ,p.Name 
        ,nc.NamesCombinations + ',' +  CAST(p.Name AS VARCHAR(MAX))                      
    FROM Person AS p JOIN NamesCombination nc ON p.Name < nc.Name
    WHERE nc.Cntr < 2  
)
SELECT NamesCombinations
FROM NamesCombination
WHERE Cntr  = 2 

enter image description here

答案 1 :(得分:1)

select P1.NAME PERSON1, P2.NAME PERSON2
  from (select rownum RNUM, NAME
        from PERSON) P1,
       (select rownum RNUM, NAME
          from PERSON) P2
 where P1.RNUM < P2.RNUM

答案 2 :(得分:0)

请注意,这是TSQL(Sql Server)语法。我知道Oracle支持窗口函数,特别是row_number(),这是此解决方案所必需的。

通过一些试验和错误让它在Oracle中运行起来应该不会太难

select p1.name, p2.name
from 
(
    select name,  row_number() over(order by name) as rownumber 
    from person
) p1
inner join
(
    select name, row_number() over(order by name) as rownumber
    from person
) p2
on p1.name <> p2.name
and p1.rownumber > p2.rownumber
order by 1

row_number为每一行分配一个行号。然后,您需要按照之前的建议加入p1.rownumber&gt;的附加连接子句。 p2.rownumber