SQL Server Pivot Example: Master Data Transformation Quickly

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.

the diagram shows how to use pivot in an application with multiple numbers and symbols
the diagram shows how to use pivot in an application with multiple numbers and symbols

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.

Impress Your Coworkers by Using SQL UNPIVOT!
Impress Your Coworkers by Using SQL UNPIVOT!

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.

SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, …
SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, …

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

SQL Server Pivot with Example
SQL Server Pivot with Example

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).

SQL Server 2012 Analysis Services Partitioning Performance Demonstration
SQL Server 2012 Analysis Services Partitioning Performance Demonstration

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>

SQL RIGHT() Explained with Examples | Extract Characters from the Right in SQL Server
SQL RIGHT() Explained with Examples | Extract Characters from the Right in SQL Server

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

SQL ROW_NUMBER() Explained with Examples | Beginner SQL Window Function Tutorial
SQL ROW_NUMBER() Explained with Examples | Beginner SQL Window Function Tutorial
an image of the server list for windows and mac oss servers, with different types of
an image of the server list for windows and mac oss servers, with different types of
SQL ORDER BY Explained with Examples | Sort Data in SQL
SQL ORDER BY Explained with Examples | Sort Data in SQL
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
Sql Cheat Sheet, Learn Sql, Learn Web Development, Excel Tutorials, Sql Server, Career Options, Data Analyst, Data Scientist, Data Analysis
SQL LIMIT Explained with Examples | Beginner SQL Tutorial
SQL LIMIT Explained with Examples | Beginner SQL Tutorial
SQL Server Export to Excel using SQL Server Import and Export Wizard
SQL Server Export to Excel using SQL Server Import and Export Wizard
💼 Most Asked SQL Interview Question!  ❓ What’s the difference between DELETE, TRUNCATE & DROP? 🚨 One keeps structure, one resets it, one wipes it out!  👉Preparing for interview? Check the Bio for playlist link  👉 Tag a friend who needs this! 🔖save it for your prep!  👉 HackerRank Topic wise SQL practice Questions: Link in Bio  Follow for daily data insights 👇 📸 Instagram | ▶️ YouTube | 📘 Facebook  . . . . . #sqlinterview #datascience #dataanalytics #sql #interviewprep #data #database #business... Interview Prep, How To Learn Sql For Data Science, Data Analyst, Computer Coding, Data Analysis Activities, Data Science Learning, Sql Programming, Job Advice, Sql Commands
💼 Most Asked SQL Interview Question! ❓ What’s the difference between DELETE, TRUNCATE & DROP? 🚨 One keeps structure, one resets it, one wipes it out! 👉Preparing for interview? Check the Bio for playlist link 👉 Tag a friend who needs this! 🔖save it for your prep! 👉 HackerRank Topic wise SQL practice Questions: Link in Bio Follow for daily data insights 👇 📸 Instagram | ▶️ YouTube | 📘 Facebook . . . . . #sqlinterview #datascience #dataanalytics #sql #interviewprep #data #database #business... Interview Prep, How To Learn Sql For Data Science, Data Analyst, Computer Coding, Data Analysis Activities, Data Science Learning, Sql Programming, Job Advice, Sql Commands
SQL in 60 days
SQL in 60 days
SQL GETDATE() Explained with Examples | Current Date & Time in SQL Server
SQL GETDATE() Explained with Examples | Current Date & Time in SQL Server
SQL UPPER() Explained with Examples | Convert Text to Uppercase in SQL
SQL UPPER() Explained with Examples | Convert Text to Uppercase in SQL
(2) Facebook Software, Engineering
(2) Facebook Software, Engineering
SQL CTE Explained with Examples | Common Table Expression Tutorial
SQL CTE Explained with Examples | Common Table Expression Tutorial
SQL LEFT() Explained with Examples | Extract Characters from the Left in SQL Server
SQL LEFT() Explained with Examples | Extract Characters from the Left in SQL Server
an info poster showing the different types of web pages and how they are used to create them
an info poster showing the different types of web pages and how they are used to create them
Search And Find All User Defined Functions / UDF In SQL Server | My Tec Bits
Search And Find All User Defined Functions / UDF In SQL Server | My Tec Bits
an image of the server list
an image of the server list
SQL REPLACE() Explained with Examples | Replace Text in SQL Server
SQL REPLACE() Explained with Examples | Replace Text in SQL Server
SQL SUBSTRING() Explained with Examples | Extract Text in SQL Server
SQL SUBSTRING() Explained with Examples | Extract Text in SQL Server
a blue and white poster with text on it
a blue and white poster with text on it
#sql #dataanalytics #powerbi #datavisualization #businessintelligence… | Vipin Chandra | 12 comments
#sql #dataanalytics #powerbi #datavisualization #businessintelligence… | Vipin Chandra | 12 comments

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!

Related Articles

Sql Pivot Example Pivot Query Sql Server Example W3 Bootcamp Reddit W3schools Aside What Is Sql Skill Sql Commit Example How Long To Learn Sql For A Job Reddit Sql Max Date In Where Clause W3 Sql Class Sql Crash Course W3