Open In App

How to Return Pivot Table Output in MySQL

Pivoting a table in MySQL involves transforming rows into columns, which can be particularly useful for data analysis and reporting. While MySQL does not have a native PIVOT function like some other database systems, you can achieve pivoting using conditional aggregation with the CASE statement.

So, In this article, we will explore how can I return pivot table output in MySQL, using the syntax, methods, methods, and some examples that will help to understand the process.



Pivot MySQL

Pivoting a table allows you to reorganize and summarize data, making it easier to analyze. In MySQL, this is accomplished by using the CASE statement within an aggregate function, typically SUM, to create conditional columns. These columns represent the pivoted values, and the result is a transformed dataset where rows become columns.

Syntax:



The general syntax for pivoting a table in MySQL involves using the CASE statement within an aggregate function, often SUM, and grouping the results by the remaining non-pivoted columns.

SELECT

non_pivoted_column,

SUM(CASE WHEN pivoted_column = ‘value1’ THEN aggregate_column END) AS value1,

SUM(CASE WHEN pivoted_column = ‘value2’ THEN aggregate_column END) AS value2,

— Additional pivoted columns as needed

FROM

your_table

GROUP BY

non_pivoted_column;

Dynamic Columns with GROUP_CONCAT

-- Dynamic Columns with GROUP_CONCAT
SET SESSION group_concat_max_len = 1000000;

SET @dynamic_columns = NULL;

SELECT GROUP_CONCAT(
DISTINCT CONCAT('SUM(CASE WHEN region = "', region, '" THEN amount END) AS "', region, '"')
) INTO @dynamic_columns
FROM sales;

SET @dynamic_sql = CONCAT(
'SELECT product, ', @dynamic_columns, ' FROM sales GROUP BY product'
);

PREPARE stmt FROM @dynamic_sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Explanation: The provided SQL dynamically generates and executes a pivot table query. The output displays aggregated sales data, with products in rows and regions as columns, showing the sum of amounts for each product and region.

Conditional Aggregation with CASE Statements

-- Conditional Aggregation with CASE Statements
SELECT
product,
SUM(CASE WHEN region = 'North' THEN amount END) AS North,
SUM(CASE WHEN region = 'South' THEN amount END) AS South
FROM
sales
GROUP BY
product;

Explanation: The output calculates the sum of amounts for each product, categorized by regions ‘North‘ and ‘South‘. Each row represents a product, and columns show the aggregated amounts for the corresponding regions.

Cross Tabulation Using Joins and Aggregate Functions

-- Cross Tabulation Using Joins and Aggregate Functions
SELECT
e.department,
SUM(CASE WHEN e.employee_id = 1 THEN e.salary END) AS Employee1,
SUM(CASE WHEN e.employee_id = 2 THEN e.salary END) AS Employee2,
SUM(CASE WHEN e.employee_id = 3 THEN e.salary END) AS Employee3,
SUM(CASE WHEN e.employee_id = 4 THEN e.salary END) AS Employee4,
SUM(CASE WHEN e.employee_id = 5 THEN e.salary END) AS Employee5
FROM
employees e
GROUP BY
e.department;

Explanation: This query performs cross-tabulation, displaying total salaries for specific employees (Employee1 to Employee5) within their respective departments. Each row represents a department, and the columns show the aggregated salaries for the specified employees in those departments.

Examples of the Return Pivot Table Output in MySQL

Example 1: Pivoting Sales Data by Region

Assume you have a table named sales with columns product, region, and amount. You want to pivot the data based on the region column.

-- Sample Data
CREATE TABLE sales (
product VARCHAR(50),
region VARCHAR(50),
amount INT
);

INSERT INTO sales VALUES ('Laptop', 'North', 1000);
INSERT INTO sales VALUES ('Laptop', 'South', 1200);
INSERT INTO sales VALUES ('Desktop', 'North', 800);
INSERT INTO sales VALUES ('Desktop', 'South', 900);
INSERT INTO sales VALUES ('Tablet', 'North', 500);
INSERT INTO sales VALUES ('Tablet', 'South', 600);

-- Pivot Query
SELECT
product,
SUM(CASE WHEN region = 'North' THEN amount END) AS North,
SUM(CASE WHEN region = 'South' THEN amount END) AS South
FROM
sales
GROUP BY
product;

Output:

product

North

South

Laptop

1000

1200

Desktop

800

900

Tablet

500

600

Example 2: Pivoting Employee Salary Data by Department

Consider a table named employees with columns employee_id, department, and salary. You want to pivot the data based on the department column.

-- Sample Data
CREATE TABLE employees (
employee_id INT PRIMARY KEY,
department VARCHAR(50),
salary INT
);

INSERT INTO employees VALUES (1, 'HR', 50000);
INSERT INTO employees VALUES (2, 'IT', 60000);
INSERT INTO employees VALUES (3, 'HR', 55000);
INSERT INTO employees VALUES (4, 'IT', 65000);
INSERT INTO employees VALUES (5, 'Finance', 70000);

-- Pivot Query
SELECT
department,
SUM(CASE WHEN employee_id = 1 THEN salary END) AS Employee1,
SUM(CASE WHEN employee_id = 2 THEN salary END) AS Employee2,
SUM(CASE WHEN employee_id = 3 THEN salary END) AS Employee3,
SUM(CASE WHEN employee_id = 4 THEN salary END) AS Employee4,
SUM(CASE WHEN employee_id = 5 THEN salary END) AS Employee5
FROM
employees
GROUP BY
department;

Output:

department

Employee1

Employee2

Employee3

Employee4

Employee5

HR

50000

0

55000

0

0

IT

0

60000

0

65000

0

Finance

0

0

0

0Q

70000

Conclusion

So, overall, pivoting tables in MySQL using conditional aggregation offers a powerful way to transform data for analysis and reporting. While MySQL doesn’t have a dedicated PIVOT function, the combination of CASE statements and aggregate functions provides a flexible solution. The additional approaches introduced, including Dynamic Columns with GROUP_CONCAT and Cross Tabulation Using Joins and Aggregate Functions, offer alternative methods for achieving pivot functionality based on specific requirements. When faced with the need to pivot data, understanding these techniques empowers MySQL users to efficiently organize and present information in a format suitable for their analytical requirements.


Article Tags :