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,
Now, use the SQL PIVOT to count all Male and Female Employees in each location,
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
Leave Comment