Implementing Pivot and Dynamic Pivot using GROUP_CONCAT() in MySQL / Blogs / Perficient


Introduction

Pivoting data is a crucial aspect of data manipulation, allowing you to transform rows into columns for better analysis. Some databases (for e.g., SQL Server) have native support for pivots, but MySQL unfortunately doesn’t support the pivot function. MySQL’s GROUP_CONCAT function is a powerful tool that can be leveraged for this purpose. In this blog, we’ll delve into the concepts of Pivot and Dynamic Pivot, providing practical stepwise examples.

 

Understanding Pivot:

Pivoting involves the transformation of row-based data into a column-based format, making it easier to analyze and comprehend. MySQL’s GROUP_CONCAT function simplifies this process by concatenating values from multiple rows into a single string.

 

Let’s consider a scenario where we have a table named sales_data with the following structure:

 

CREATE TABLE sales_data (

    product_id INT,

    month VARCHAR(10),

    revenue DECIMAL(10, 2)

);

Let’s ingest some sample data:

Picture1

To pivot the data to showcase monthly revenues for each product, we can use the GROUP_CONCAT function:

SELECT

    product_id,

    GROUP_CONCAT(

        CONCAT(month, ‘: ‘, revenue) ORDER BY month

Data Intelligence - The Future of Big Data
The Future of Big Data

With some guidance, you can craft a data platform that is right for your organization’s needs and gets the most return from your data capital.

Get the Guide

    ) AS monthly_revenues

FROM sales_data

GROUP BY product_id;

This query groups the data by product_id and concatenates the monthly revenues, producing a result where each row represents a unique product with its corresponding monthly revenues.

Picture2

Dynamic Pivot:

Dynamic Pivot takes pivoting to the next level by allowing the column headers to be determined dynamically at runtime. This is particularly useful when dealing with datasets where the column values are not known in advance.

Consider a scenario where you want to pivot the sales data dynamically based on the distinct months present in the table. Here’s how you can achieve that:

SET SESSION group_concat_max_len = 1000;

SET @sql = NULL;

SELECT

    GROUP_CONCAT(

        DISTINCT CONCAT(

            ‘MAX(CASE WHEN month = “‘, month, ‘” THEN revenue END) AS “‘, month, ‘”‘

        )

    )

INTO @sql

FROM sales_data;

 

SET @sql = CONCAT(

    ‘SELECT product_id, ‘, @sql, ‘ FROM sales_data GROUP BY product_id;’

);

 

PREPARE stmt FROM @sql;

EXECUTE stmt;

DEALLOCATE PREPARE stmt;

This query groups the data by product_id based on the distinct months present in the sales_data table. It then prepares and executes the statement, resulting in a pivoted table with columns dynamically named after each distinct month.

Picture3

Conclusion:

Pivoting and dynamic pivoting are powerful techniques in MySQL that can significantly enhance data analysis. The use of GROUP_CONCAT, along with proper ordering and dynamic SQL generation, allows for flexible and efficient transformations of data.





Source link

Social media & sharing icons powered by UltimatelySocial
error

Enjoy Our Website? Please share :) Thank you!