Question

I have a reference data table having columns as codes and values.

For e.g. there are three code types viz. A, B, C.

The table is as below:

Code      Value
---------------------
 A1       a_one
 A2       a_two
 B1       b_one
 B2       b_two
 B3       b_three
 C1       c_one
 C2       c_two
 C3       c_three
 C4       c_four
---------------------

I have a requirement where the input will be code types and output should be all permutations between the input code types.

For e.g. if the input code types are A and C, the output of my sql should be:

col_1     col_2
---------------------
 A1       C1
 A1       C2
 A1       C3
 A1       C4
 A2       C1
 A2       C2
 A2       C3
 A2       C4
---------------------

Similarly if the input code types is A, B, C, the output of the sql will have three columns with all the permutations between A, B, C viz. A1 B1 C1 to A2 B3 C4.

I have no idea how to start on this. So any hints will be useful.

Thanks for reading!

Was it helpful?

Solution

If I understand your question correctly, this is one of those rare cases where a CROSS JOIN is actually what you want. A CROSS JOIN will give you the Cartesian product of two sets, which means all possible combinations between the values in those sets.

Example:

  • Table A with column 1 contains values 'a' and 'b'
  • Table B with column 2 contains values 'c' and 'd'

The following CROSS JOIN query (note there is no 'join condition' specified, on purpose):

SELECT  *
FROM    A
CROSS JOIN B

will return the following result:

1   2
--------
a   c
a   d
b   c
b   d

I created an SQL Fiddle to show you a possible solution. You can tweak it a bit to see if this is what you need. (Note it's an Oracle fiddle, as there is no DB2 option.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top