articles

Home / DeveloperSection / Articles / Define the PIVOT Table with examples in SQL server.

Define the PIVOT Table with examples in SQL server.

Define the PIVOT Table with examples in SQL server.

Ashutosh Kumar Verma 190 05-Jul-2024

SQL Server PIVOT

A PIVOT table in SQL Server is a way to convert data from rows to columns, grouping values ​​as needed. It is particularly useful for collecting and analyzing data in a readable format.

Syntax-

SELECT *
FROM (
   -- Subquery that retrieves the data to pivot
   SELECT <non-pivoted column(s)>,
          <pivot column>,
          <value column>
   FROM <source_table>
) AS SourceTable
PIVOT (
   -- PIVOT function parameters
   <aggregate_function>(<value column>)
   FOR <pivot column> IN (<column1>, <column2>, ... <columnN>)
) AS PivotTable;

Example- 

Let's see we have a sample SQL table “EmployeeDetails” that contains information about Employees,

Define the PIVOT Table with examples in SQL server.

 

Now, use the SQL PIVOT to count all Male and Female Employees in each location, 

Define the PIVOT Table with examples in SQL server.

 

Note:
Aggregation Functions: The most common aggregation functions used in PIVOT are SUM, COUNT, AVG, MIN, and MAX.


Dynamic Pivot: If the values ​​of the pivot column (ProductName, TransactionDate in the example above) are already dynamic or unknown, you may need to use dynamic SQL to create the pivot column dynamically


Using PIVOT in SQL Server can greatly simplify data analysis tasks where data needs to be summarized and presented in a cross-tabular format. Change the instances based on your specific data structure and aggregation needs.

 

Also, Read: Explain the SQL Server backups and their types


Hi! This is Ashutosh Kumar Verma. I am a software developer at MindStick Software Pvt Ltd since 2021. I have added some new and interesting features to the MindStick website like a story section, audio section, and merge profile feature on MindStick subdomains, etc. I love coding and I have good knowledge of SQL Database.

Leave Comment

Comments

Liked By