Mysql
 sql >> Database >  >> RDS >> Mysql

Tabella pivot MySQL con java

Puoi utilizzare l'SQL dinamico per ruotare dinamicamente come

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; 

Demo