sql >> Base de Datos >  >> RDS >> Mysql

Tabla dinámica de MySQL usando Java

Puede usar SQL dinámico para pivotar dinámicamente como

SET @sql = NULL;
SET @date = '2020-11-30';

SELECT GROUP_CONCAT(
             CONCAT(
                    'SUM(CASE WHEN Partners = "', Partners,'" THEN Amount ELSE 0 END ) AS'
                    ,Partners
                    )
       )
  INTO @sql
  FROM ( SELECT DISTINCT Partners FROM BPFinal WHERE Date = @date ) AS b;

SET @sql = CONCAT('SELECT Branch,',@sql,
                   ' FROM BPFinal
                    WHERE Date = "',@date,'"' 
                  ' GROUP BY Branch'); 
                  
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt; 

Demostración