Skip to content
Advertisement

Transpose using column names in Oracle SQL

I have worked a bit in pivot/unpivot in Oracle SQL but this one seems little complex and need some help here. the below is my table design

year Comp_A_prev_yr_due_ct Comp_A_prev_yr_due_amt Comp_A_curr_yr_due_ct Comp_A_Curr_yr_due_amt
2019 100 1000 101 1001

like this I have multiple companies as columns (each as a set of 4) and the report needs to be kinda be reader friendly

Company year due_ct due_amt prev_or_curr
A 2019 100 1000 prev
A 2019 101 1001 cur

any help is gold here!!!! thanks

Advertisement

Answer

Are you looking for something like this?

SELECT regexp_substr(company_prev_curr, '(.*?_){1}(.*?)_', 1, 1,'', 2) AS company
    ,year
    ,due_ct
    ,due_amt
    ,regexp_substr(company_prev_curr, '(.*?_){2}(.*?)_', 1, 1,'', 2) AS prev_curr
FROM test
unpivot(
        (due_ct,due_amt) 
         FOR company_prev_curr IN (
            (Comp_A_prev_yr_due_ct,Comp_A_prev_yr_due_amt),
            (Comp_A_curr_yr_due_ct,Comp_A_Curr_yr_due_amt)
            )
        ) u;

Demo on db<>fiddle

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