I would like to perform lookup based on the number of Yes in Input.
In ID No.1, Output1 is A because it is first Yes, Output2 is B because it is second Yes. In ID No.2, Output1 is blank because Input1 is n/a, subsequent output is based on number of Yes appeared. In ID No.3, it shows counting is skipped when the Input2 is not Yes. (so Output3 is H)
Are there any way to do the recursive counting? (Or the only way to find Output3 is to list all 4 possible scenarios? (blank, from Col1, from Col2 and from Col3?)
I would be grateful if I can a way to do it recursively because I have more than 10 input columns.
ID Col1 Col2 Col3 Input1 Input2 Input3 Output1 Output2 Output3 1 A B C Yes Yes No A B (null) 2 D E F n/a Yes Yes (null) D E 3 G H I Yes No Yes G (null) H
Advertisement
Answer
Use CASE
statement to calculate output as following:
Select id, Col1, Col2, Col3, Input1, Input2, Input3, Case when input1= 'Yes' then col1 end as output1, Case when input2= 'Yes' then col2 end as output2, Case when input3= 'Yes' then col3 end as output3 From your_table
— Update —
Try this version where I have used REGEXP_SUBSTR
and CASE
statement as follows:
SELECT ID, COL1, COL2, COL3, INPUT1, INPUT2, INPUT3, REGEXP_SUBSTR(OUTPUT, '[^,]', 1, 1) AS OUTPUT1, REGEXP_SUBSTR(OUTPUT, '[^,]', 1, 2) AS OUTPUT2, REGEXP_SUBSTR(OUTPUT, '[^,]', 1, 3) AS OUTPUT3 FROM ( SELECT ID, COL1, COL2, COL3, INPUT1, INPUT2, INPUT3, CASE WHEN INPUT1 = 'Yes' THEN COL1 || ',' END || CASE WHEN INPUT2 = 'Yes' THEN COL2 || ',' END || CASE WHEN INPUT3 = 'Yes' THEN COL3 || ',' END AS OUTPUT FROM YOUR_TABLE );
Cheers!!