Oracle 11G - Unpivot

Oracle 11g: Unpivot multiple columns and include column name

Just select idnum, sk, f, e, h, 'F'||SK as col_name ... You need to specify all columns instead of an asterix.

Like this http://sqlfiddle.com/#!4/12446/21

Oracle SQL - Unpivot kind of logic but without hard coding

Use UNPIVOT:

SELECT *
FROM table_name
UNPIVOT (
(string, amount) FOR type IN (
(debit_string, debit_amount ) AS 'D',
(credit_string, credit_amount) AS 'C'
)
);

Which, for the sample data:

CREATE TABLE table_name (Debit_String, Credit_String, Debit_Amount, Credit_Amount) AS
SELECT 'ING1', 'ING2', 123, 0 FROM DUAL UNION ALL
SELECT 'INT2', 'INT5', 234, 0 FROM DUAL;

Outputs:
































TYPESTRINGAMOUNT
DING1123
CING20
DINT2234
CINT50

Oracle 11g - Unpivot

Use this query:

with t (Dat, Year, Month, Day, Turn_1, Turn_2, Turn_3) as (
select sysdate, 2014, 08, 28, 'Foo', 'Bar', 'Xab' from dual
)
select dat, year, month, day, turn, source from t
unpivot (
source for turn in (Turn_1, Turn_2, Turn_3)
)

DAT YEAR MONTH DAY TURN SOURCE
----------------------------------------------
08/01/2014 2014 8 28 TURN_1 Foo
08/01/2014 2014 8 28 TURN_2 Bar
08/01/2014 2014 8 28 TURN_3 Xab

Unpivot coumns into rows - PL/ SQL

You have to use Union all to include the duplicate:

Demo

Result:

Sample Image

SELECT ID, A_1 A, B_1 B FROM TABLE1
UNION ALL
SELECT ID, A_2, B_2 FROM TABLE1
UNION ALL
SELECT ID, A_3, B_3 FROM TABLE1 ORDER BY ID;

Oracle 11g unpivot very slow - low performance

One thing to try is to use WITH clause for the base query.

Instead of

SELECT * from (SELECT my_data, ...) UNPIVOT (...) 

Try

WITH base as (select my_data, ...) select * from base UNPIVOT (...)

In my case it reduced query time by a factor of 10.

pivot/unpivot oracle sql query with more than 2 resulting columns

You can unpivot multiple columns:

...
UNPIVOT INCLUDE NULLS (
(value1, startdate)
FOR code in (
(Math, MathStartDate) as 'Math',
(Science, ScienceStartDate) as 'Science',
(Comp, CompStartDate) as 'Comp',
(Hist, HistStartDate) as 'Hist'
)
);
CODE    | VALUE1 | STARTDATE
------- | ------ | ---------
Math | 12 | 12-NOV-20
Science | 13 | 02-NOV-20
Comp | 6 | 01-NOV-20
Hist | 45 | 01-NOV-20

db<>fiddle



Related Topics



Leave a reply



Submit