Monday 16 February 2015

Display rows into columns using PIVOT in oracle 11g


We can use PIVOT Keyword to display rows into columns and UNPIVOT Keyword to display column into rows to generate result in crosstab format.

PIVOT:

General Syntax :


Pivot_clause -> Which defines the columns to be aggregated
Pivot_for_clause->Which defines the columns to be grouped and pivoted
Pivot_in_clause ->Which defines the filter for the columns

Example:
Requirement: Need a query to display number of order created each day of the week and total count of the order for that week.
Expected output :


The table oe_order_headers_all consists order creation date . We have developed below query to get the output (Here we have taken the data only for the year 2014)

Query:


Output(Without PIVOT):


Output(With PIVOT):



UNPIVOT:
It is exactly opposite to PIVOT

General Syntax:


unpivot_clause: this clause specifies a name for a column to represent the unpivoted measure values.

unpivot_for_clause: the unpivot_for_clause specifies the name for the column that will result from our unpivot query.

unpivot_in_clause: this contains the list of pivoted columns to be unpivoted.

No comments: