PostgreSQL: CREATE PIVOT TABLE to arrange Rows into Columns form

In this post, I am going to demonstrate arrangement of the row data to columns which is called a something like Pivot table in PostgreSQL.

What is a Pivot Table?

postgresql pivot tablePivot table is one kind of summary and representation of data, like Microsoft Spreadsheets.

Pivot table arranges some of row categories into column and also create count and average of that data for better representation.

Like Microsoft SQL Server, PostgreSQL doesn’t provide a feature like Pivot Table, We can achieve using SQL Query.

Create a table with sample data:

Examine this data where two employees with working hour in a different department.
In this data, employee worked more than one time in some of the department.
Now requirement is, to populate different column for different department with total of working hours.

SQL Query to PIVOT Table (Using GroupBy Clause):

The Result:

In the above result,

You can see the result of two employees with total working hour by each department.

The first step is inner query, in which we have selected employee working hour base on department category.

The Second step is to select this data in the outer query and apply group by clause for SUM ().

Anvesh Patel

Leave a Reply

Be the First to Comment!

Notify of