With a little help of code that creates code for you, you might create a view and fetch data in a simple manner.
Sample data (up to "4"; didn't feel like doing it for "30" values):
SQL> select * from cdhisttbl;
ID CODE_1 CODE_1_DAT CODE_2 CODE_2_DAT CODE_3 CODE_3_DAT CODE_4 CODE_4_DAT
------ ------ ---------- ------ ---------- ------ ---------- ------ ----------
J12999 AB99 15.01.2022 CD18 08.02.2023 ZM32 01.03.2023 DE15 18.08.2023
K25882 FP99 05.04.2022 GH18 02.03.2023 FP18 03.10.2023 AB99 08.07.2023
J12999 MM99 25.06.2022 NN18 28.04.2023 GX23 02.05.2023 AB99 28.01.2023
F87324 GL99 15.02.2022 ZZ18 18.03.2023 GH18 12.07.2023 AX19 18.04.2023
Values you're interested in (ID = J12999 and CODE_X
= 'AB99') are in
- row 1 (
CODE_1
with date equal to 15.01.2022)
- row 3 (
CODE_4
with date equal to 28.01.2023)
Code that writes code for you (in the last line, you'd use 30
instead of 4
as your table has 30 codes):
SQL> select 'select id, ' || level || ' as code#, code_' || level ||' as code, code_' || level ||
2 '_date as code_date from cdhisttbl union all ' as query
3 from dual
4 connect by level <= 4;
QUERY
------------------------------------------------------------------------------------------
select id, 1 as code#, code_1 as code, code_1_date as code_date from cdhisttbl union all
select id, 2 as code#, code_2 as code, code_2_date as code_date from cdhisttbl union all
select id, 3 as code#, code_3 as code, code_3_date as code_date from cdhisttbl union all
select id, 4 as code#, code_4 as code, code_4_date as code_date from cdhisttbl union all
Now, copy/paste that output and use it while creating a view (add the 1st line and remove trailing union all
):
SQL> create or replace view v_cdhisttbl as
2 select id, 1 as code#, code_1 as code, code_1_date as code_date from cdhisttbl union all
3 select id, 2 as code#, code_2 as code, code_2_date as code_date from cdhisttbl union all
4 select id, 3 as code#, code_3 as code, code_3_date as code_date from cdhisttbl union all
5 select id, 4 as code#, code_4 as code, code_4_date as code_date from cdhisttbl;
View created.
That's it; the rest is trivial:
SQL> select *
2 from v_cdhisttbl
3 where id = 'J12999'
4 and code = 'AB99';
ID CODE# CODE CODE_DATE
------ ---------- ---- ----------
J12999 1 AB99 15.01.2022 --> code_1 and code_1_date
J12999 4 AB99 28.01.2023 --> code_4 and code_4_date
contain values you're looking for
Though, consider what @LoztInSpace said and redesign that table. That's not the way it should look like.