Are you working with SQL and wish to transform rows into columns for a more readable and convenient format? You're in the right place. In this guide, we'll explore how to pivot rows to columns in SQL, including multiple columns, with practical examples and step-by-step instructions.

Before we dive in, it's essential to understand that SQL uses the `PIVOT` and `UNPIVOT` functions to convert rows into columns or columns into rows. In this article, we'll focus on the `PIVOT` function, which rotates rows into columns based on a specific column value.

Understanding the SQL PIVOT Function
The SQL `PIVOT` function takes a table, a column to use as the pivot (the value that will become the new column headers), and a column or expression to aggregate (the value that will populate the new columns). By using this function, you can efficiently transform your data structure.

To illustrate this, let's consider a simple table named `Sales` with the following structure and data:
| Country | Product | Sales |
|---|---|---|
| USA | ProductA | 10 |
| USA | ProductB | 20 |
| UK | ProductA | 30 |

Pivoting a Single Column
Let's start by pivoting the `Sales` column based on the `Country` column. We'll use the following query:
```sql SELECT * FROM ( SELECT Country, Product, Sales FROM Sales ) AS P PIVOT ( SUM(Sales) FOR Product IN ([ProductA], [ProductB]) ) AS PV; ```
In this query, we use the `SUM` function to aggregate the `Sales` column. We list the values we want to use as new column headers inside the `IN` clause, separating them with commas.

The resulting table will look like this:
| Country | ProductA | ProductB |
|---|---|---|
| USA | 10 | 20 |
| UK | 30 | NULL |
Pivoting Multiple Columns

Now, let's pivot multiple columns, including the `Sales` column. We'll modify the previous query as follows:
```sql SELECT * FROM ( SELECT Country, Product, Sales FROM Sales ) AS P PIVOT ( SUM(Sales) FOR Product IN ([ProductA], [ProductB]) ) AS PV PIVOT ( COUNT(Product) FOR Country IN ([USA], [UK]) ) AS PV2; ```
In this query, we nest the `PIVOT` function twice. First, we pivot the `Sales` column based on the `Product` column. Then, we pivot the result again based on the `Country` column, this time using the `COUNT` function to aggregate the number of occurrences for each product in each country.



















The resulting table will look like this:
| Country | ProductA_Sales | ProductB_Sales | ProductA_Count | ProductB_Count |
|---|---|---|---|---|
| USA | 10 | 20 | 1 | 1 |
| UK | 30 | NULL | 1 | 0 |
Dynamic Pivoting with SQL
Often, you'll need to create a dynamic query that can handle any number of columns or column names. To achieve this, you can use a combination of the `PIVOT` function, dynamic SQL, and the `FOR XML PATH` clause to generate a list of column names.
The `FOR XML PATH` clause returns the column values as a string, which allows you to generate dynamic SQL by concatenating strings and using the `EXEC` command. However, this approach requires SQL Server 2005 or later and may have performance limitations for large datasets.
Dynamic Pivoting with a Single Column
To illustrate dynamic pivoting, let's start by pivoting a single column. We'll use the following query to create a dynamic pivot with the `Sales` column based on the `Country` column:
```sql DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX), @tableName AS NVARCHAR(MAX) = 'Sales'; SET @cols = STUFF((SELECT distinct ',' + QUOTENAME([Product]) FROM Sales FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') SET @query = 'SELECT Country, ' + @cols + ' from ( SELECT Country, Product, Sales FROM ' + @tableName + ' ) x PIVOT ( SUM(Sales) FOR Product IN (' + @cols + ') ) p '; EXEC(@query); ```
In this query, we first create a list of distinct product names using the `FOR XML PATH` clause and store it in the `@cols` variable. Then, we generate the dynamic SQL query in the `@query` variable. Lastly, we execute the dynamic query using the `EXEC` command.
The resulting table will have the same structure as the previous static pivot example, with the `Sales` column for each product as a separate column.
Dynamic Pivoting with Multiple Columns
Dynamic pivoting with multiple columns follows a similar approach. You'll need to adjust the `FOR XML PATH` clause and the dynamic SQL query to handle multiple columns. However, keep in mind that nesting dynamic pivots may lead to increased complexity and potential performance issues.
The final dynamic pivot with multiple columns query would look like this:
```sql -- (The full query is too large to display here, but you can extend the previous single column dynamic pivot query to handle multiple columns following the same logic) ```
While dynamic pivoting offers flexibility in handling any number of columns, it's essential to be cautious when working with large datasets or complex queries. Always verify the performance implications and consider alternative approaches, such as using conditional aggregations or persisted computed columns, when appropriate.
In conclusion, the SQL `PIVOT` function is a powerful tool for transforming rows into columns, allowing you to present your data in a more readable and convenient format. By understanding the basics of the `PIVOT` function and exploring dynamic pivoting, you can efficiently handle various data structures and requirements in your SQL queries. Happy coding!