Thursday, November 19, 2015

Change orientation of table, (Rotate table) rows to column

Some time we also use the terms to "denormalize rows" / "row flattening", here is sample query which can gave the fare idea to accomplish this task with the help of query.

Actual result:
select row_number() over(partition by deptno  order by 1) as rn, ename,deptno
from emp
where deptno = 10
/

   RN ENAME                    DEPTNO
----- -------------------- ----------
    1 CLARK                        10
    2 KING                         10
    3 MILLER                       10


Required result:
1  with t as
  2  (
  3     select
  4             row_number() over(partition by deptno  order by 1) as rn,
  5             ename,
  6             deptno
  7     from emp
  8     where deptno = 10)
  9  select ename1,ename2,ename3 from
 10  (
 11  (select ename  as ename1 ,deptno  from t where rn = 1) e1
 12  left outer join
 13  (select ename  as ename2 ,deptno from t where rn = 2) e2 on e2.deptno= e1.deptno
 14  left outer join
 15* (select ename  as ename3 ,deptno from t where rn = 3) e3 on e3.deptno= e1.deptno)
SQL> /

ENAME1               ENAME2               ENAME3
-------------------- -------------------- --------------------
CLARK                KING                 MILLER


No comments:

Post a Comment

web stats