获得所有可能的组合

时间:2013-09-30 12:07:57

标签: sql algorithm sorting select combinations

我有数据库

|x1|y1|z1|c1|

我想提取所有可能的组合,如:

x1 
x1 y1
x1 z1 
x1 c1 
x1 y1 z1 
x1 y1 c1 
x1 z1 c1
x1 y1 z1 c1 
y1
y1 z1 
y1 c1
y1 z1 c1 
z1 
z1 c1 
c1 

我如何使用SQL做到这一点?

1 个答案:

答案 0 :(得分:0)

with combi (old, new) as                                     
(select 'x1y1z1c1', '               ' from sysibm/sysdummy1  
 union all                                                   
 select substr(old, 3),                                      
        strip(new) concat substr(old, 1, 2) from combi       
        where locate(substr(old, 1, 2), new) = 0             
 union all                                                   
 select substr(old, 1, 2) concat substr(old, 5),             
        strip(new) concat substr(old, 3, 2) from combi       
        where locate(substr(old, 3, 2), new) = 0             
 union all                                                   
 select substr(old, 1, 4) concat substr(old, 7),             
        strip(new) concat substr(old, 5, 2) from combi       
        where locate(substr(old, 5, 2), new) = 0             
 union all                                                   
 select substr(old, 1, 6),                                   
        strip(new) concat substr(old, 7, 2) from combi       
        where locate(substr(old, 7, 2), new) = 0    
)                                                   
select distinct new                                 
from   combi