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

Dynamisk pivot 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

Her er den dynamiske version

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




  1. PostgreSQL:Tid til oprettelse af tabel

  2. mysql load testværktøjer

  3. Sådan fungerer INTERSECT i PostgreSQL

  4. Sådan kontrolleres, om brugeren allerede eksisterer i MySQL med PHP