MySQL pivot row into dynamic number of columns|How to Create dynamic pivot query in mysql

Sample Procedure:
create procedure DynamicPivot(
    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;

    SET @sql = CONCAT('SELECT Pv.', 
        columnB, 
        ', ', 
        @sql, 
        ' FROM ', tableB, ' Pv GROUP BY Pv.',
        columnB,'');
  
    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END

Execute Procedure:
CALL DynamicPivot(@tableA:='table1',@columnA:='Col1',
@tableB:='table2',@columnB:='Col2');

Post a Comment

0 Comments