给定表:
create table Person( Name varchar(100) )
其中Name是所有人唯一
什么SQL查询可以生成所有可能的N!/((N-2)!2!)循环赛的组合?
假设人的基数始终等于4
例如人= { '安娜', '的Jerome', '帕特里克', '迈克尔')
输出:
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
下面是该问题的两种解决方案
SELECT t1.Name + ',' + t2.Name AS NamesCombination
FROM Person t1
INNER JOIN Person t2
ON t1.Name < t2.Name
OR(甲骨文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
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
请注意,这是TSQL(SQL Server)的语法。 我知道Oracle支持窗口函数,特别是ROW_NUMBER(),这是必要的这一解决方案。
它不应该太难得到这个在甲骨文工作的一些试验和错误
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额外加入条款