如何从数据库“ x”的同一列中返回值的所有可能组合的列表?例如,我有:
col 1, 1 2 3 4
我想返回所有可能组合的列表,例如,
1,2 1,3 1,4 2,3, 2,4 3,4
....
您尚未说明正在使用哪个RDBMS,或者您是否要将组合限制为仅包含集合的2个元素。
这是使用分层查询的Oracle答案:
SQL小提琴
Oracle 11g R2架构设置 :
CREATE TABLE TEST ( COL ) AS SELECT LEVEL FROM DUAL CONNECT BY LEVEL < 5;
查询1 :
SELECT SUBSTR(SYS_CONNECT_BY_PATH(COL, ','), 2) AS combination FROM TEST CONNECT BY PRIOR COL < COL
结果 :
| 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 |
查询2 :
SELECT SUBSTR(SYS_CONNECT_BY_PATH(COL, ','), 2) AS combination FROM TEST WHERE LEVEL = 2 CONNECT BY PRIOR COL < COL AND LEVEL <= 2
| COMBINATION | |-------------| | 1,2 | | 1,3 | | 1,4 | | 2,3 | | 2,4 | | 3,4 |
以及使用递归CTE的SQL Server版本:
MS SQL Server 2014架构设置 :
CREATE TABLE TEST ( COL INT ); INSERT INTO TEST SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4;
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
| 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 |