Pivoting data in SQL Server can be a powerful tool to transform the structure of data for easier analysis or presentation. It allows you to flip rows into columns and vice versa, summarizing data based on specific criteria. Let's dive into an example to illustrate this.

Consider a simple sales tableесwith columns: OrderID, ProductName, QuantitySold, and SaleDate. You want to know the total quantity sold for each product on a daily basis. Here's how you can achieve this using the `PIVOT` function.

Creating the Pivot Table
First, let's understand the basic syntax of the `PIVOT` function. It takes a single row of data from a source table and converts it into multiple rows based on the specified values.

Now, let's create a pivot table. We'll use the `PIVOT` function along with the `SUM` aggregate function to get the total quantity sold for each product on a daily basis.
Pivoting by Days

Here's the SQL query to create the pivot table:
<pre>SELECT ProductName, [2022-01-01], [2022-01-02], [2022-01-03] FROM ( SELECT ProductName, CAST(SaleDate AS VARCHAR(10)) AS 'SaleDate', QuantitySold FROM Sales ) AS src PIVOT ( SUM(QuantitySold) FOR SaleDate IN ([2022-01-01], [2022-01-02], [2022-01-03])) AS pvt</pre>
In this query, the inner select statement formats the data to be pivoted. The `PIVOT` function then converts the 'SaleDate' column into columns for each of the specified dates (2022-01-01, 2022-01-02, and 2022-01-03).

Pivoting by Weeks
You can also pivot data by weeks. Here's how you can modify the previous query to pivot by weeks:
<pre>SELECT ProductName, [Week 1], [Week 2], [Week 3] FROM ( SELECT ProductName, DATENAME(dw, SaleDate) AS 'WeekNum', SUM(QuantitySold) AS TotalSales FROM Sales GROUP BY ProductName, DATENAME(dw, SaleDate) ) AS src PIVOT ( SUM(TotalSales) FOR WeekNum IN ([Week 1], [Week 2], [Week 3])) AS pvt</pre>

In this query, we first group the data by the name of the day of the week. We then use the `PIVOT` function to create columns for each of the weeks.
Dynamic Pivot Tables




















While the previous examples work well, they have a limitation - the columns in the pivot table are static and need to be specified in the query. To overcome this, you can use dynamic SQL in SQL Server to create pivot tables with dynamic columns.
Creating a dynamic pivot table involves generating a Dynamic SQL query, executing it to create a temporary table, and then selecting data from that table. This process is complex and beyond the scope of this introduction, but it's a powerful tool for creating advanced pivot tables.
Mastering SQL Server's `PIVOT` function can greatly enhance your data analysis and presentation capabilities. It allows you to slice and dice your data in ways that might not be possible with standard SQL queries. Keep practicing and exploring to become a SQL Server expert!