【问题标题】:Get all possible combinations获取所有可能的组合
【发布时间】:2013-10-06 07:06:00
【问题描述】:

我有数据库

|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 来做到这一点?

【问题讨论】:

  • 天哪,不。不要尝试在 SQL 中实现这一点。改用应用程序 - 并且有许多排列和子集选择的标准实现。
  • 试图理解这一点。你的意思是你有一个数据库表,其中一个字段包含指定的 4 条记录?
  • 您确实应该考虑使用存储过程或在应用程序级别解决此问题。但是,您可以实现这个基本连接表,包含一列值SELECT DISTINCT t1.v, t2.v... FROM (SELECT DISTINCT COLUMN1 v FROM TABLE) t1, (SELECT DISTINCT COLUMN2 v FROM TABLE) t2...

标签: sql algorithm sorting select combinations


【解决方案1】:
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                                        

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2011-05-16
    • 1970-01-01
    • 1970-01-01
    • 2021-08-17
    • 2012-03-20
    相关资源
    最近更新 更多