MySQL pivot table query with dynamic columns

后端 未结 3 1579
一个人的身影
一个人的身影 2020-11-21 22:12

I\'m using the following tables for storing product data:

mysql> SELECT * FROM product;
+---------------+---------------+--------+
| id | name     | descr         


        
3条回答
  •  醉酒成梦
    2020-11-21 22:51

    Here's stored procedure, which will generate the table based on data from one table and column and data from other table and column.

    The function 'sum(if(col = value, 1,0)) as value ' is used. You can choose from different functions like MAX(if()) etc.

    delimiter //
    
      create procedure myPivot(
        in tableA varchar(255),
        in columnA varchar(255),
        in tableB varchar(255),
        in columnB varchar(255)
    )
    begin
      set @sql = NULL;
        set @sql = CONCAT('select group_concat(distinct concat(
                \'SUM(IF(', 
            columnA, 
            ' = \'\'\',',
            columnA,
            ',\'\'\', 1, 0)) AS \'\'\',',
            columnA, 
                ',\'\'\'\') separator \', \') from ',
            tableA, ' into @sql');
        -- select @sql;
    
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
    
        DEALLOCATE PREPARE stmt;
        -- select @sql;
    
        SET @sql = CONCAT('SELECT p.', 
            columnB, 
            ', ', 
            @sql, 
            ' FROM ', tableB, ' p GROUP BY p.',
            columnB,'');
    
        -- select @sql;
    
        /* */
        PREPARE stmt FROM @sql;
        EXECUTE stmt;
        /* */
        DEALLOCATE PREPARE stmt;
    end//
    
    delimiter ;
    

提交回复
热议问题