简体   繁体   中英

Single Table MySQL Pivot with Dynamic Column

I want to transform row of mysql table to column, through mysql pivot table My input table. My input table which has data in below format.

Area    Status   User
-----------------------
1       Active   user1
1       Failed   user2
1       Success  user4
2       Active   user2
2       Failed   user3
2       Success  user4

My Desired Output Format is below

Status   user1     user2   user3    user4
-----------------------------------------
Active   1         1       0         0
Failed   0         1       1         0
Success  0         0       0         2

Since i do not know the exact number of users i want to pivot it through dynamic column only.

in your case, if you have a separate user table, you can easily make a Cartesian Product between your user table and status table, and make pivoting.. if you need further helps let me know..

have look on one of my following blog post about a pivoting schenerio for sales report, I am using a dynamic calendar table to produce Cartesian Product with Order Category table.. Sample Pivoting and Cartesian Product

I have another runnable example for you, from

product_id  supplier_id number      price
p1          s1          2           2.12
p1          s2          3           3.12
p2          s1          4           4.12

to

product_id  supplier_id1        supplier_id2        number1         number2             price1              price2
p1              s1              s2                  2               3                   2.12                3.12
p2              s1              NULL                4               NULL                4.12                NULL

here the "supplier_id" is dynamic, it could be one little data set from a 1 million big set.so there could be supplier1,or supplier99,or supplier999,depends on whats in the source table. first, lets create the source table:

CREATE TABLE test
(
    product_id varchar(10),
    supplier_id varchar(10),
    number int(11),
    price decimal(10,2)
);
INSERT INTO test (product_id, supplier_id, number, price) VALUES ('p1', 's1', 2, 2.12);
INSERT INTO test (product_id, supplier_id, number, price) VALUES ('p1', 's2', 3, 3.12);
INSERT INTO test (product_id, supplier_id, number, price) VALUES ('p2', 's1', 4, 4.12);

I don't think one select will do it, so the temp table and column are needed, this code is what you need:


DROP TABLE IF EXISTS  final_data;
DROP TABLE IF EXISTS  temp_data;
CREATE  TEMPORARY TABLE temp_data
    SELECT
           product_id,
           IF(@productid = product_id, @rownum := @rownum + 1, @rownum := 1) seller_number,
           @productid := product_id,
           supplier_id,
           number,
           price
    FROM
         test
           CROSS JOIN (SELECT @rownum := 0) r
           CROSS JOIN (SELECT @productid:="") n
    ORDER BY
             product_id ASC;

ALTER TABLE temp_data ADD PRIMARY KEY(product_id, seller_number);
ALTER TABLE temp_data ADD INDEX (seller_number);

#Dynamic Pivot starts via prepared statements
#Step 1: Dynamily create colum names for sql
#Field supplier_id
SET @sql = NULL;
SELECT
       GROUP_CONCAT(DISTINCT
                    CONCAT(
                      ' MAX(IF( seller_number= ''',
                      seller_number,
                      ''', supplier_id, NULL)) AS ',
                      CONCAT("supplier_id", seller_number)
                        )
           ) INTO @sql
FROM temp_data;

#Field number
SELECT
       CONCAT(@sql, ', ',
              GROUP_CONCAT(DISTINCT
                           CONCAT(
                             ' MAX(IF( seller_number= ''',
                             seller_number,
                             ''', number, NULL)) AS ',
                             CONCAT("number", seller_number)
                               )
                  ) )INTO @sql
FROM temp_data;

#Field price
SELECT
       CONCAT(@sql, ', ',
              GROUP_CONCAT(DISTINCT
                           CONCAT(
                             ' MAX(IF( seller_number= ''',
                             seller_number,
                             ''', price, NULL)) AS ',
                             CONCAT("price", seller_number)
                               )
                  ) )INTO @sql
FROM temp_data;

#Step 2: Add fields to group by query
SET @sql = CONCAT(' create table final_data as (SELECT
                        product_id,
                        ', @sql, '
                    FROM
                        temp_data
                    GROUP BY
                        product_id)  ');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DROP TABLE IF EXISTS  temp_data;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM