Home > Database > Mysql Tutorial > How to Dynamically Pivot Data in MySQL Using Prepared Statements?

How to Dynamically Pivot Data in MySQL Using Prepared Statements?

Mary-Kate Olsen
Release: 2025-01-06 07:36:40
Original
601 people have browsed it

How to Dynamically Pivot Data in MySQL Using Prepared Statements?

Dynamic Pivoting in MySQL Using Prepared Statements

MySQL lacks a native PIVOT function, but you can emulate it using aggregate functions and CASE statements. For dynamically pivoting data, prepared statements offer an efficient solution.

Consider a scenario with a table of product parts:

CREATE TABLE Parts (
    part_id INT,
    part_type VARCHAR(1),
    product_id INT
);
INSERT INTO Parts (part_id, part_type, product_id) VALUES
(1, 'A', 1),
(2, 'B', 1),
(3, 'A', 2),
(4, 'B', 2),
(5, 'A', 3),
(6, 'B', 3);
Copy after login

The desired output is a pivoted table summarizing the part IDs for each product:

product_id  part_A_id  part_B_id
----------  ----------  ----------
1           1          2
2           3          4
3           5          6
Copy after login

Dynamic Pivoted Query

SET @sql = NULL;
SELECT GROUP_CONCAT(DISTINCT
    CONCAT(
        'max(case when part_type = ''',
        part_type,
        ''' then part_id end) AS part_',
        part_type, '_id'
    )
) INTO @sql
FROM Parts;
SET @sql = CONCAT('SELECT product_id, ', @sql, ' 
                  FROM Parts 
                   GROUP BY product_id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Copy after login

Static Pivoted Query (Limited Columns)

For a static query with a fixed number of pivot columns:

SELECT product_id,
    max(CASE WHEN part_type = 'A' THEN part_id END) AS part_A_id,
    max(CASE WHEN part_type = 'B' THEN part_id END) AS part_B_id
FROM Parts
GROUP BY product_id;
Copy after login

The above is the detailed content of How to Dynamically Pivot Data in MySQL Using Prepared Statements?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template