Oracle pl / sql置换和组合

时间:2015-12-03 03:03:55

标签: sql oracle stored-procedures plsql

我不确定这个搜索字词是什么,请告诉我是否已有答案。 例如: 我有这些数据

A
B
C
D
E

计算每种可能组合的添加的最佳方法是什么?如:

A
A+B
A+C
A+D
A+E
A+B+C
A+B+D
A+B+E
A+C+D
A+C+E
A+C+D+E
A+B+C+D
A+B+C+E
A+B+C+D+E
B
B+C
B+D
B+E
B+C+D
B+C+E
B+C+D+E
C
C+D
C+E
...
The list goes on.......

有没有办法实现这个目标?

5个数据不固定。我可能有10 .. 20或50或1000 :(

谢谢。

2 个答案:

答案 0 :(得分:2)

在SQL中,您几乎可以使用这组left join s:

执行此操作
select (t1.col + coalesce(t2.col, 0) + coalesce(t3.col, 0) +
        coalesce(t4.col, 0) + coalesce(t5.col, 0)
       ) as sumcombo
from t t1 left join
     t t2
     on t1.col < t2.col left join
     t t3
     on t2.col < t3.col left join
     t t4
     on t3.col < t4.col left join
     t t5
     on t4.col < t5.col;

它不太有用,因为你永远不会只获得“A”。代替:

with t as (
      select col
      from table
      union all
      select NULL
      from dual
     )
select (t1.col + coalesce(t2.col, 0) + coalesce(t3.col, 0) +
        coalesce(t4.col, 0) + coalesce(t5.col, 0)
       ) as sumcombo
from table t1 left join
     t t2
     on t1.col < t2.col or t2.col is null left join
     t t3
     on t2.col < t3.col or t3.col is null left join
     t t4
     on t3.col < t4.col or t4.col is null left join
     t t5
     on t4.col < t5.col or t5.col is null;

答案 1 :(得分:1)

这可以通过分层查询来解决。首先,为连接构建另一个子列col2

-- your test data set
with testdata as
 (select 'A' as col from dual
  union
  select 'B' from dual
  union
  select 'C' from dual
  union
  select 'D' from dual
  union
  select 'E' from dual),

-- create child column
testdata2 as
 (select t.col as col1, t.col as col2 from testdata t)

select level, sys_connect_by_path(col1, '/') path
  from testdata2 t
connect by prior col1 < col2
 order by level, sys_connect_by_path(col1, '/');

结果:

1   /A
1   /B
1   /C
1   /D
1   /E
2   /A/B
2   /A/C
2   /A/D
2   /A/E
2   /B/C
2   /B/D
2   /B/E
2   /C/D
2   /C/E
2   /D/E
3   /A/B/C
3   /A/B/D
3   /A/B/E
3   /A/C/D
3   /A/C/E
3   /A/D/E
3   /B/C/D
3   /B/C/E
3   /B/D/E
3   /C/D/E
4   /A/B/C/D
4   /A/B/C/E
4   /A/B/D/E
4   /A/C/D/E
4   /B/C/D/E
5   /A/B/C/D/E