PIVOT clause in Orcale

PIVOT and UNPIVOT clause in Oracle - this is something I learnt recently.

PIVOT and UNPIVOT is introduced from Oracle 11g version.
This post will explain about PIVOT clause in Oracle.

PIVOT

Assume a scenario as below.

You have a table which stores some parameter information. it has two columns called PARAMETER_NAME and PARAMETER_VALUE those are used to save parameter names and values.
Now you get a requirement, that you need to create a new view  from old table. But, in this new view, there should be a separate column for each parameter. 

To achieve this requirement, you can get help of PIVOT clause.

PIVOT clause is allowed you to transpose the rows in a table to columns by aggregating the data.
Hence, PIVOT clause returns the more columns and fewer rows than the starting data set (table).

Syntax for PIVOT clause.

SELECT 
    col0, col1, col2
FROM 
    table_name
PIVOT 
(
  aggregate_function(col2)
  FOR col1
  IN ( expr1, expr2, ... expr_n)
)



  • Pivot clause - column that you want to aggregate with oracle aggregate function ex: SUM, MAX, MIN, COUNT, AVG

                AGGREGATE_FUNCTION(col2)


  • Pivot for clause - The column you want to Pivot
                FOR col1

  • Pivot in clause - Values of the col1 that need to transpose to columns.
               IN ( expr1, expr2, ... expr_n)

PIVOT clause perform implicit ORDER_BY based on the all other selected columns those are not defined in the PIVOT clause.

Example


Old table.

CREATE TABLE PIVOT_TEST
( id number(10) NOT NULL,
  parameter_name varchar2(50) NOT NULL,
  parameter_value varchar2(50)
);

Data in PIVOT_TEST will look like as below.



You can create a query as below to fetch the data from tables with using PIVOT clause. 

WITH old AS
   (
      SELECT id, parameter_name, parameter_value
        FROM PIVOT_TEST
   )
   SELECT * FROM old
   PIVOT
   (
      MAX(parameter_value)
      FOR parameter_name IN
      (
          'MAX_VALUE' AS max_value,
          'MIN_VALUE' AS min_value,
          'OPERATION_METH' AS operation_meth,
          'CONNECTOR_TYPE' AS connector_type
      )
    )

Here, I have used MAX as the aggregate function. MAX or MIN aggregate functions can be used, when you want to show original values of the columns as it is. This MIN and MAX aggregate functions are mostly used with non numeric values.

Then the result will be as below.









Comments

Popular posts from this blog

How to add standard and custom Metadata to PDF using iTextSharp

How to set and get Metadata to image using BitmapMetadata class in C#

How to generate direct line token to start a new conversation between your own client application and bot framework in Java