Return all possible combinations of values within a single column in SQL

时间:2015-06-26 10:01:38

标签: sql

How do I return a list of all possible combinations of values from within the same single column of database 'x'? For example I have:

    col 1,
    1
    2
    3
    4

And I would like to return a list of all possible combinations like,

    1,2
    1,3
    1,4
    2,3,
    2,4
    3,4

....

2 个答案:

答案 0 :(得分:9)

You've not said which RDBMS you are using or whether you want to limit the combinations to just 2 elements of the set.

Here is an Oracle answer using hierarchical queries:

SQL Fiddle

Oracle 11g R2 Schema Setup:

CREATE TABLE TEST ( COL ) AS
SELECT LEVEL FROM DUAL CONNECT BY LEVEL < 5;

Query 1:

SELECT SUBSTR(SYS_CONNECT_BY_PATH(COL, ','), 2) AS combination
FROM TEST
CONNECT BY PRIOR COL < COL

Results:

| COMBINATION |
|-------------|
|           1 |
|         1,2 |
|       1,2,3 |
|     1,2,3,4 |
|       1,2,4 |
|         1,3 |
|       1,3,4 |
|         1,4 |
|           2 |
|         2,3 |
|       2,3,4 |
|         2,4 |
|           3 |
|         3,4 |
|           4 |

Query 2:

SELECT SUBSTR(SYS_CONNECT_BY_PATH(COL, ','), 2) AS combination
FROM   TEST
WHERE  LEVEL = 2
CONNECT BY PRIOR COL < COL AND LEVEL <= 2

Results:

| COMBINATION |
|-------------|
|         1,2 |
|         1,3 |
|         1,4 |
|         2,3 |
|         2,4 |
|         3,4 |

And an SQL Server version using a recursive CTE:

SQL Fiddle

MS SQL Server 2014 Schema Setup:

CREATE TABLE TEST ( COL INT );

INSERT INTO TEST
          SELECT 1
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4;

Query 1:

WITH cte ( combination, curr ) AS (
  SELECT CAST( t.COL AS VARCHAR(80) ),
         t.COL
  FROM   TEST t
  UNION ALL
  SELECT CAST( c.combination + ',' + CAST( t.col AS VARCHAR(1) ) AS VARCHAR(80) ),
         t.COL
  FROM   TEST t
         INNER JOIN
         cte c
         ON ( c.curr < t.COL )
)
SELECT combination FROM cte

Results:

| combination |
|-------------|
|           1 |
|           2 |
|           3 |
|           4 |
|         3,4 |
|         2,3 |
|         2,4 |
|       2,3,4 |
|         1,2 |
|         1,3 |
|         1,4 |
|       1,3,4 |
|       1,2,3 |
|       1,2,4 |
|     1,2,3,4 |

答案 1 :(得分:7)

select concat(t1.id, ",", t2.id) from t t1 join t t2 on t1.id < t2.id;

An SQL Fiddle example can be found here.