Thursday, November 12, 2009

Combinations Algo

I wanted to achieve following, produce data under OUT for a given IN.


------------------------------------
IN => OUT
------------------------------------
1  => 1
2  => 1,2, 1+2
3  => 1,2,3, 1+2,1+3,2+3, 1+2+3
------------------------------------
.

This algo has its uses when doing matching sets. For example, you have a set D, and there are three details A, B and C. D could be matched with details in any one way

1. A
2. B
3. C
4. AB
5. BC
6. AC
7. ABC
.
With 10g, achieving this is super-easy. Just one SQL would get you all possible combinations.

SELECT SYS_CONNECT_BY_PATH ( GT.seq_number, ',') col_val
   FROM (SELECT ROWNUM seq_number
           FROM all_objects 
          WHERE ROWNUM <= &p_num_dtls ) GT 
CONNECT BY TO_NUMBER(GT.seq_number) > PRIOR TO_NUMBER(GT.seq_number)
If you need to separate out each element at each level, you can use delimstring_to_table function, search on this blog and you would find it.

Cheers.

No comments: