SQL - 创建所有可能的组合

时间:2015-01-22 11:37:14

标签: sql sql-server

我的课程很少,我想创建所有可能的组合。

班级表

ColA
A
B
C
D
E

输出(不是如果我有A,B作为输出我不想要B,A等等)

ColA    Col2 
A        B
A        C
A        D
A        E
B        C
B        D
B        E
C        D
C        E
D        E

我不想使用游标。

3 个答案:

答案 0 :(得分:6)

您可以通过添加条件来执行此操作:

select c1.cola as col1, c2.cola as col2
from class c1 join
     class c2
     on c1.cola < c2.cola;

答案 1 :(得分:2)

CREATE TABLE #a (a CHAR(1));
INSERT INTO #a VALUES ('A');
INSERT INTO #a VALUES ('B');
INSERT INTO #a VALUES ('C');
INSERT INTO #a VALUES ('D');
INSERT INTO #a VALUES ('E');

SELECT a.a, b.a FROM #a a CROSS JOIN #a b
--If you do not need the same combinations such as AA then do like that
SELECT a.a, b.a FROM #a a CROSS JOIN #a b  WHERE a.a <> b.a

答案 2 :(得分:2)

试试这个

DECLARE @t TABLE ( ID CHAR(1) )

INSERT  INTO @t VALUES  ( 'A' )
INSERT  INTO @t VALUES  ( 'B' )
INSERT  INTO @t VALUES  ( 'C' )
INSERT  INTO @t VALUES  ( 'D' )
INSERT  INTO @t VALUES  ( 'E' )

;WITH    cte
          AS ( SELECT   ID ,
                        ROW_NUMBER() OVER ( ORDER BY (SELECT 1) ) AS rn
               FROM     @t
             )
    SELECT  t1.ID ,
            t2.ID
    FROM    cte t1
            JOIN cte t2 ON t2.rn > t1.rn
    ORDER BY t1.ID ,
            t2.ID