Sunday, February 14, 2010

Split 1 record into 3 or more without self join or union

Time to time it is neccessary to display 2-3 or more records based on a single source record from the table. It happens when a single record contains different types of information. Using UNION or join seems like an option, but from the performance perspective it is a bad solution. Below is an example of the row containing 3 different type of information. Each should be retreived as a separate record. Using WITH clause can do the trick.
It is not really flexible assuming that number of records to display are static.

Example is below:
1. Create test table: create table test_splt_table (pk Number,ssn Varchar2(10),objtype1 Number,obj1value Varchar2(100),objtype2 date,obj1value Varchar2(100),obj3type Number,obj3value Varchar2(100));

2. insert into test_splt_table(101,'123-11-2222',1,'Jack',2,'12-Apr-1980',3,'1000');
insert into test_splt_table(103,'120-22-3333',1,'Jolie',2,'16-Jun-1960',3,'2000');

3. Final select

with a as (select level l from dual connect by level<=3)
select pk,ssn,decode(a.l,1,objtype1,2,objtype2,3,objtype3) type,
decode(a.l,1,obj1value,2,obj2value,3,obj3value) Value
from test_splt_table,a

0 comments:

Post a Comment