The PIVOT function in SQL is a powerful tool that allows you to rotate or transpose data in a tabular format. It's particularly useful when you want to display results in a summarized, easy-to-read manner. Here's a comprehensive guide on how to use it effectively.

Before diving into the examples, it's essential to understand the basic syntax. The PIVOT function has two forms: PIVOT and UNPIVOT. Here, we'll focus on the PIVOT function, which follows this general structure:

Understanding the PIVOT Function Syntax
The basic syntax for the PIVOT function is:

SELECT * FROM PIVOT(...)
where:

- Column to Aggregate: This is the column you want to group by and pivot.
- Column to Pivot: This is the column you want to rotate or transpose.
- Value Column: This is the column that contains the values you want to aggregate.
Applying PIVOT to a Simple Query
Let's start with a simple example using a hypothetical 'Sales' table that has 'Category', 'Year', and 'Sales' columns.

Suppose we want to display sales data for each category across two years (2020 and 2021). Here's how you can do it:
SELECT Category, [2020], [2021]
FROM (
SELECT Category, Year, Sales
FROM Sales
) AS Ԁ
PIVOT(
SUM(Sales)
FOR Year IN ([2020], [2021])
)AS давт
Pivoting Data by Multiple Columns

In the previous example, we pivoted data based on a single column ('Year'). However, you can also pivot data by multiple columns.
Pivoting Data by Two Columns




















Let's modify the previous example to pivot data by both 'Year' and 'Quarter'. We'll use the UNPIVOT function to first convert our columns into rows and then pivot them.
Here's the modified query:
SELECT Category, Quarter, [Jan], [Feb], [Mar]
FROM (
SELECT Category, Quarter, Month, Sales
FROM Sales
) AS Ԁ
PIVOT(
AVG(Sales)
FOR Month IN ([Jan], [Feb], [Mar])
)AS давт
Handling NULL Values
When using the PIVOT function, you might encounter NULL values if there's no data for a specific category or year. To handle this, you can use the COALESCE function to replace NULL with zeros.
For example:
SELECT Category, [2020], [2021]
FROM (
SELECT Category, Year, Sales
FROM Sales
) AS Ԁ
PIVOT(
SUM(COALESCE(Sales, 0))
FOR Year IN ([2020], [2021])
)AS давт
Understanding and using the PIVOT function effectively can greatly enhance your SQL skills and make your reports more informative and user-friendly.