Skip to content
Advertisement

Search each value of Column A in Column B in SQL Oracle

Let’s say I have this type of dataset:

Consider the following conditions:

In row 1, Num_B "95000" appears in Num_A (row 3) and the correspondent Num_A (row 1) "94000" is equal to its Num_B (row 3) (which is the case `”94000″)

So the new column Comm_1 will have the combination of Num_A and Num_B as its value. Same goes for Comm_2

As for Comm_3, the condition are same as Comm_1 or Comm_2, and an additional condition that Reg_1 (or Reg_2) of row 1 'AAA' (or 'CCC') is equal to Reg_1 or Reg_2 of row 3 (which is the case).

I want to construct a query so that the result would look like this:

I tried the following basic syntax but it isn’t working:

So please provide any hint and point me to reading about the right point in pl/sql or what ever procedure I need to learn.

Advertisement

Answer

You can get what (I think) you want with outer self joins:

(I’ve left in row_num just to keep the display order the same, it isn’t used otherwise; I assume that isn’t actually a column in your table.)

The comm_1 value is based on a left join to another row which has its num_a matching this row’s num_b.

The comm_2 value is based on a left join to another row which has its num_a matching this row’s num_c.

The comm_3 value is the same as comm_1 but has to also match its reg_1 with the other row’s reg_2 or vice versa. But, this calculates row 3’s value as 9500094000 rather than the 94009500 shown in the question – not clear which is right though.

This will also get duplicate rows if there is more than one match for any of the outer joins; that isn’t the case with your sample data, but something to watch out for. I have no idea how you would want to handle that if it can happen.


You could also do it with a single outer join and more logic/aggregation in the column expressions:

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement