SQL Pivot Rows to Columns Multiple Examples Tutorial

When dealing with SQL databases, transitioning rows to columns can vastly improve data presentation and simplify analysis. This process, known as pivoting, is particularly useful when working with datasets that have repeated measures or when you need to compare data from multiple categories side-by-side. This article guides you through pivoting rows to columns using the PIVOT and CONDITIONAL AGGREGATE functions in SQL, with a focus on handling multiple categories.

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

Before delving into the pivot process, let's consider a scenario where we have sales data from different regions (West, East, South, North) over three years. The data is structured with one row per region per year. Our goal is to consolidate this data into a single row per year, with columns for each region's sales.

>SQL : Multiple Row and Column Subqueries - w3resource
>SQL : Multiple Row and Column Subqueries - w3resource

Pivoting using PIVOT Function

Microsoft SQL Server's PIVOT function is a straightforward way to transform rows into columns. It's ideal for aggregating and presenting data in a tabular format, making it perfect for our scenario.

SQL in 60 days
SQL in 60 days

The PIVOT function's primary argument is a column expression that you wish to transform into columns. The UNPIVOT function, its counterpart, does the oppositeβ€”it converts columns into rows.

Preparing Data: Creating a Sample Table

SQL Basics Every Beginner Must Know | Database, Table, Row & Column Explained
SQL Basics Every Beginner Must Know | Database, Table, Row & Column Explained

The first step in pivoting involves ensuring your data is structured correctly. Let's create a sample table named 'Sales' with the following statement:

```sql CREATE TABLE Sales ( Region VARCHAR(10), Year INT, Sales INT ); ```

Insert some sample data:

```sql INSERT INTO Sales (Region, Year, Sales) VALUES ('West', 2020, 50000), ('East', 2020, 70000), ('South', 2020, 90000), ('North', 2020, 60000), ('West', 2021, 55000), ('East', 2021, 65000), ('South', 2021, 75000), ('North', 2021, 58000), ('West', 2022, 60000), ('East', 2022, 78000), ('South', 2022, 95000), ('North', 2022, 62000); ```

Using the PIVOT Function

a table with numbers and symbols on it that says,'s the number functions for each
a table with numbers and symbols on it that says,'s the number functions for each

With our data prepared, let's pivot the 'Sales' table using the PIVOT function. Here's how:

```sql SELECT Year, [West], [East], [South], [North] FROM (SELECT Region, Year, Sales FROM Sales) AS PivotTable PIVOT (SUM(Sales) FOR Region IN ([West], [East], [South], [North])) AS PivotResult; ```

The PIVOT function takes the 'Sales' column from our subquery and transforms it into pivot columns based on the 'Region' column. The 'IN' clause lists the column names to create in the result set.

Pivoting using Conditional Aggregate Functions

a table that has some words on it
a table that has some words on it

MySQL and PostgreSQL don't have a PIVOT function, but you can achieve similar results using conditional aggregation. The CASE expression is crucial in this process.

Let's use conditional aggregation to pivot the same 'Sales' table from our SQL Server example.

What is the rows and range Between in a Frame Clause?
What is the rows and range Between in a Frame Clause?
SQL Joins Explained for Beginners
SQL Joins Explained for Beginners
SQL Circle πŸ’ͺ
SQL Circle πŸ’ͺ
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
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL - Select all columns that satisfy a specific condition
SQL - Select all columns that satisfy a specific condition
SQL queries don
SQL queries don
Learn SQL just by investing 30 minutes a day within 30 Days
Learn SQL just by investing 30 minutes a day within 30 Days
SQL ROW_NUMBER() Explained with Examples | Beginner SQL Window Function Tutorial
SQL ROW_NUMBER() Explained with Examples | Beginner SQL Window Function Tutorial
167K views Β· 467 reactions | Brought to you by programmingvalley  #SQL #database | Programming Valley
167K views Β· 467 reactions | Brought to you by programmingvalley #SQL #database | Programming Valley
an image of a diagram with the words,'the sq circle'in different languages
an image of a diagram with the words,'the sq circle'in different languages
SQL Joins Explained πŸš€ | Beginner Data Analyst SQL Guide
SQL Joins Explained πŸš€ | Beginner Data Analyst SQL Guide
The Essential Guide to SQL’s Execution Order - KDnuggets
The Essential Guide to SQL’s Execution Order - KDnuggets
SQL Table Structure Explained for Beginners πŸ“Š
SQL Table Structure Explained for Beginners πŸ“Š
SQL Aggregate Functions Made Easy πŸ“Š | SUM, COUNT, AVG, MAX, MIN with Examples
SQL Aggregate Functions Made Easy πŸ“Š | SUM, COUNT, AVG, MAX, MIN with Examples
SQL IN NUTSHELL
SQL IN NUTSHELL
#sql #sqlfordataanalysis #dataanalytics #learnsql #datascience #sqltips #database | Ruth Y.
#sql #sqlfordataanalysis #dataanalytics #learnsql #datascience #sqltips #database | Ruth Y.
four different types of soljoins with the names and numbers in each section on them
four different types of soljoins with the names and numbers in each section on them
SQL JOINS Made Easy πŸ”— | INNER, LEFT, RIGHT & FULL JOIN with Examples
SQL JOINS Made Easy πŸ”— | INNER, LEFT, RIGHT & FULL JOIN with Examples

Using SUM and CASE in MySQL

In MySQL, you can use the SUM function along with a CASE statement to create pivot columns. Here's how:

```sql SELECT Year, SUM(CASE Region WHEN 'West' THEN Sales ELSE NULL END) AS `West`, SUM(CASE Region WHEN 'East' THEN Sales ELSE NULL END) AS `East`, SUM(CASE Region WHEN 'South' THEN Sales ELSE NULL END) AS `South`, SUM(CASE Region WHEN 'North' THEN Sales ELSE NULL END) AS `North` FROM Sales GROUP BY Year; ```

Using SUM and CASE in PostgreSQL

PostgreSQL's approach is similar to MySQL, with slight syntax differences:

```sql SELECT Year, SUM(CASE Region WHEN 'West' THEN Sales ELSE NULL END) "West", SUM(CASE Region WHEN 'East' THEN Sales ELSE NULL END) "East", SUM(CASE Region WHEN 'South' THEN Sales ELSE NULL END) "South", SUM(CASE Region WHEN 'North' THEN Sales ELSE NULL END) "North" FROM Sales GROUP BY Year; ```

Remember to wrap column names in backticks (`` ` ``) when there's a space, as in MySQL, or double quotes (") in PostgreSQL.

The final step in your data transformation journey is to understand and practice these techniques. Pivoting can take your data analysis to the next level, making it more accessible and insightful. Happy coding!

Related Articles

Pivot Table In Sql Server Management Studio What Is The Maximum Date In Sql Server Sql Max Date Group By Sql Pivot Rows To Columns Dynamic Sql Max Datetime Value W3schools Asp.net Core Types Of Transactions In Sql Server W3schools Asm Sql Pivot Table W3schools Create Table Sql With Primary Key