Mysql
 sql >> Base de Dados >  >> RDS >> Mysql

Pivot dinâmico MySQL

SELECT id,SUM(CASE WHEN Item='Chocolate' THEN Purchased END) as Chocolate_Purchased,
SUM(CASE WHEN Item='Biscuit' THEN Purchased END) as Biscuit_Purchased,
SUM(CASE WHEN Item='Jelly' THEN Purchased END) Jelly_Purchased,
SUM(CASE WHEN Item='Mile' THEN Purchased END) as Mile_Purchased 
GROUP BY id

Aqui está a versão dinâmica
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
    CONCAT(
      'SUM(IF(t.item = ''',
      item,
      ''', t.purchased, 0)) AS ',
      item
    )
   )INTO @sql
FROM t;

SET @sql = CONCAT('SELECT id,
                     ', @sql, ' 
                   FROM t               
                   GROUP BY id');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

FIDDLE