Monday, October 25, 2010

Oracle 11g - Pivot and UnPivot - Split rows into Multiple colums or vice versa

Transposing rows into columns (pivot) or columns into rows (unpivot) to generate results in crosstab format. Pivoting is a very useful technique, especially for reporting.



 I/P:

--------- Table1



Location    Month      Balances

------------------ -----------

A1               1                 100

A1               2                 200

A1               3                 300

A1               4                 400

A1               5                 500

A1               6                 600

A1               7                 800


 Output

----------------



Location         1           2           3          4        5        6        7

----------     ---        ----         ---       ---        ---     ----    -----
 A1             100       200         300      400     500      600     800



Sample Sql :
------------

 SELECT location,month,balances from table 1
  PIVOT (balances           -- pivot_clause
         FOR month         -- pivot_for_clause
         IN  (1,2,3,4,5,6,7)  -- pivot_in_clause
        );



 UNPIVOT:-
 --------

 Try it: same as pivot (instead of Pivot use Unpivot)

No comments: