Skip to content
Advertisement

How to use wm_concat one a column that already exists in the query?

So… I am currently using Oracle 11.1g and I need to create a query that uses the ID and CusCODE from Table_with_value and checks Table_with_status using the ID to find active CO_status but on different CusCODE.

This is what I have so far – obviously does not work as it should unless CusCODE and ID are provided manually:

SELECT wm_concat(CoID) as active_CO_Status_for_same_ID_but_different_CusCODE
FROM Table_with_status
WHERE 
CoID IN (SELECT CoID FROM Table_with_status WHERE ID = Table_with_value.ID AND CusCODE != Table_with_value.CusCODE)) AND Co_status = 'active';

Table_with_value:

|CoID | CusCODE | ID | Value |
|--------|---------|----------|----|
|354223 | 1.432 | 0784296L | 99 |
|321232 | 4.212321.22 | 0432296L | 32 |
|938421 | 3.213 | 0021321L | 93 |

Table_with_status:

|CoID | CusCODE | ID | Co_status|
|--------|--------------|----------|--------|
|354223 | 1.432 | 0784296L | active|
|354232 | 1.432 | 0784296L | inactive |
|666698 | 1.47621 | 0784296L | active |
|666700 | 1.5217 | 0784296L | active |
|938421 | 3.213 | 0021321L | active |
|938422 | 3.213 | 0021321L | active |
|938423 | 3.213 | 0021321L | active |
|321232 | 4.212321.22 | 0432296L | active |
|321232 | 4.212321.22 | 0432296L | active |
|321232 | 1.689 | 0432296L | inactive |

Expected output:

|CoID | active_CO_Status_for_same_ID_but_different_CusCODE  | ID | Value |
|--------|---------|----------|----|
|354223 | 666698,666700 | 1.432 | 0784296L | 99 |
|321232 | N/A | 4.212321.22 | 0432296L | 32 |
|938421 | N/A | 3.213 | 0021321L | 93 |

Any idea on how this can be implemented ideally without any PL/SQL for loops, but it should be fine as well since the output dataset is expected < 300 IDs.

I apologize in advance for the cryptic nature in which I structured the question 🙂 Let me know if something is not clear.

Advertisement

Answer

From your description and expected output, it looks like you need a left outer join, something like:

SELECT v.CoID,
  wm_concat(s.CoID) as other_active_CusCODE -- active_CO_Status_for_same_ID_but_different_CusCODE
  v.CusCODE,
  v.ID,
  v.value
FROM Table_with_value v
LEFT JOIN Table_with_status s
ON s.ID = v.ID
AND s.CusCODE != v.CusCODE
AND s.Co_status = 'active'
GROUP BY v.CoID, v.CusCODE, v.ID, v.value;

SQL Fiddle using listagg() instead of the never-supported and now-removed wm_concat(); with a couple of different approaches if the logic isn’t quite what I interpreted. With your sample data they all get:

COID   OTHER_ACTIVE_CUSCODE CUSCODE     ID       VALUE
------ -------------------- ----------- -------- -----
321232 (null)               4.212321.22 0432296L    32
354223 666698,666700        1.432       0784296L    99
938421 (null)               3.213       0021321L    93
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement