3

给定表:

create table Person( Name varchar(100) )

其中 Name 对于所有 Person 都是唯一的

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

假设 Person 的基数总是等于 4

示例人 = {'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
4

3 回答 3

1

这里有两个解决问题的方法

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

或(甲骨文 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 

在此处输入图像描述

于 2012-11-14T03:31:03.957 回答
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
于 2012-11-14T05:03:16.567 回答
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 > p2.rownumber 的附加连接子句

于 2012-11-14T03:56:33.547 回答