Mysql
 sql >> Datenbank >  >> RDS >> Mysql

MySQL-Pivot-Tabelle mit Java

Sie können dynamisches SQL verwenden, um dynamisch zu pivotieren, z. B.

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