I have a query that returns a table that looks somewhat like below.
In the image, I want the Input table to look like the Output table —
Essentially, I want all the data from columns to get transposed into rows. But I do not want to convert rows into columns.
I have seen solutions to transpose rows and columns but wanted to check if there is something easier out there that anyone knows of. Any help appreciated!
TIA
Advertisement
Answer
Like you already know to convert rows
to columns
PIVOT
is required , similarly to convert columns
to rows
we need UNPIVOT
.
As there is no specific table with column names specified I have used WITH
clause to create a temporary table to demonstrate. Here is link to know more about the clauses used in UNPIVOT
for your reference.
with table1 as ( select 'Inbound' department, 50 hour0, 44 hour1, 29 hour2, 47 hour3, 17 hour4 from dual union all select 'Outbound', 6, 4, 10, 24, 39 from dual union all select 'Returns', 3, 1, 39, 43, 35 from dual ) select * from table1 t1 unpivot (value for hour in (hour0 as '0',hour1 as '1',hour2 as '2',hour3 as '3',hour4 as '4'))