Master the SQL Pivot Function with Practical Examples

In the realm of data manipulation, the PIVOT function in SQL offers a powerful tool for transforming data from rows to columns. This function is particularly useful when you want to consolidate and summarize data for better comprehension. Let's dive into an example to grasp how the SQL PIVOT function works.

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

Before delving into the specifics, let's first understand the structure of a PIVOT query. A PIVOT query in SQL essentially consists of two main parts - an aggregation function (like SUM, COUNT, AVG) and a value column which holds the data that we want to aggregate.

SQL IN A NUTSHELL
SQL IN A NUTSHELL

SQL PIVOT Function Syntax

The basic syntax for the SQL PIVOT function is as follows:

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

SELECT column_name, [pivot_column_name_from_your_source_data] FROM table_name PIVOT (pivot_function(pivot_column_name_in_your_source_data, aggregate_function) FOR pivot_column_name_from_your_source_data IN ([pivot_column_values]) ORDER BY order_column_name;

Understanding each element

SQL Aggregate Functions Made Easy ๐Ÿ“Š | SUM, COUNT, AVG, MAX, MIN with Examples
SQL Aggregate Functions Made Easy ๐Ÿ“Š | SUM, COUNT, AVG, MAX, MIN with Examples

The syntax isn't entirely intuitive, so let's break it down. The main parts are the columns we want to pivot (the ones we choose with 'FOR' and 'IN'), and the pivot function itself, which involves choosing an aggregate function, like SUM or AVG.

The 'IN' clause is where you list the columns you want to pivot. It defines the columns for which you want to compute the aggregate function. These must be the distinct values from the pivot column.

Example: A PIVOT Query in Action

SQL Aggregate Functions Cheat Sheet for Beginners
SQL Aggregate Functions Cheat Sheet for Beginners

Let's consider a simple table of sales data:

SalesData Salesperson | Product | QuantitySold --------------------------- John | ProductA | 50 Anna | ProductB | 70 John | ProductC | 30 Anna | ProductA | 60

We want to see how much of each product both John and Anna sold. We would use the following SQL:

the pivot function in excel is displayed on a sheet of paper with numbers and symbols
the pivot function in excel is displayed on a sheet of paper with numbers and symbols

SELECT product_name, [John], [Anna] FROM SalesData PIVOT (SUM(quantity_sold) FOR salesperson IN ([John], [Anna]))

Transforming the Output with PIVOT

SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, โ€ฆ
SQL Pivot in all databases: MySQL, MariaDB, SQLite, PostgreSQL, Oracle, โ€ฆ
SQL Aggregate Functions Tutorial | COUNT, SUM, AVG, MIN & MAX Examples
SQL Aggregate Functions Tutorial | COUNT, SUM, AVG, MIN & MAX Examples
There are three types of window function families ๐Ÿ 
There are three types of window function families ๐Ÿ 
SQL IN NUTSHELL
SQL IN NUTSHELL
Window Functions in SQL
Window Functions in SQL
SQL Window Functions Explained with Examples | Beginner SQL Tutorial
SQL Window Functions Explained with Examples | Beginner SQL Tutorial
Standard SQL Functions CHEAT SHEET
Standard SQL Functions CHEAT SHEET
SQL Aggregate Functions Cheatsheet
SQL Aggregate Functions Cheatsheet
the three functions for ranking data in an excel spreadsheet with numbers and symbols
the three functions for ranking data in an excel spreadsheet with numbers and symbols
SQL String Functions and Pattern Matching
SQL String Functions and Pattern Matching
the top 10 sol queries to master windows functions for each employee in their department
the top 10 sol queries to master windows functions for each employee in their department
the pivot tables basics poster is shown in green and white, with text on it
the pivot tables basics poster is shown in green and white, with text on it
SQL Window Functions use a sliding frame ๐ŸชŸโคต
SQL Window Functions use a sliding frame ๐ŸชŸโคต
SQL SUM() Explained with Examples | Beginner SQL Tutorial
SQL SUM() Explained with Examples | Beginner SQL Tutorial
SQL COUNT() Function Explained | COUNT(*), COUNT(Column), COUNT(DISTINCT)
SQL COUNT() Function Explained | COUNT(*), COUNT(Column), COUNT(DISTINCT)
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL LAG() Explained with Examples | Beginner SQL Window Function Tutorial
SQL MIN() Explained with Examples | Beginner SQL Tutorial
SQL MIN() Explained with Examples | Beginner SQL Tutorial
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
an image of a computer screen with the text, stop using sum function without know how to
an image of a computer screen with the text, stop using sum function without know how to
What is the rows and range Between in a Frame Clause?
What is the rows and range Between in a Frame Clause?

The PIVOT function doesn't just work with sums. It can also handle counts, averages, and even retrieve specific values. Let's apply PIVOT to get a count of products sold by each salesperson.

Counting Products

To do this, simply adjust the pivot function. Instead of SUM, use COUNT.

SELECT product_name, [John], [Anna] FROM SalesData PIVOT (COUNT(quantity_sold) FOR salesperson IN ([John], [Anna]))

Getting Product Names

If needed, you can even modify the PIVOT function to return specific product names. Here is an example where PIVOT is used to display the unique product names sold by each salesperson:

SELECT salesperson, [ProductA], [ProductB], [ProductC] FROM SalesData PIVOT (MAX(product_name) FOR product IN ([ProductA], [ProductB], [ProductC]))

The flexibility of the PIVOT function makes it an excellent tool for transforming complex datasets into understandable, actionable information. Understanding how to use PIVOT effectively can significantly enhance your SQL skills and help you design more powerful queries.

Mastering the SQL PIVOT function can ultimately help you to make data-informed decisions more efficiently. So what are you waiting for? Dive into your data, and happy pivoting!"

Related Articles

Sql Server Begin Transaction Commit Example Sql Transaction Commit Rollback Example Sql Pivot And Unpivot In Same Query W3schools Ascii Sql Create Table Foreign Key Example Pivot And Unpivot Sql Server How To Use Pivot Table In Sql Server With Example Pivot Table In Sql Server Example Sql Max Datetime Create Table Sql With Foreign Key Constraint