Mayou
Mayou

Reputation: 8818

Converting a pivot table to flat table in Oracle SQL

Consider the following table:

enter image description here

I am using the query below (in SQL Server) to convert this table to a flat table as follows: enter image description here

I would like to the same thing using Oracle SQL. However the query does not work in "Oracle SQL" language: cross apply, which is used below, does not work in Oracle. Any idea how to write this equivalently using Oracle SQL? Thanks!

select t.employee_id,
   t.employee_name,
   c.data,
   c.old,
   c.new
 from test_table t
 cross apply
 (
   select 'Address', Address_Old, Address_new union all
   select 'Income', cast(income_old as varchar(15)), cast(income_new as varchar(15))
 ) c (data, old, new)

Upvotes: 0

Views: 522

Answers (1)

Andrew G
Andrew G

Reputation: 2496

Not quite as succinct without the ability to do CROSS APPLY:

select t.employee_id,
t.employee_name,
c.data,
DECODE (c.data, 'Address', t.address_old, 'Income', t.income_old) AS old,
DECODE (c.data, 'Address', t.address_new, 'Income', t.income_new) AS new
from test_table t
cross join
(
  select 'Address' AS data
  from dual
  union all
  select 'Income'
  from dual
 ) c

Upvotes: 1

Related Questions