Mysql
 sql >> Teknologi Basis Data >  >> RDS >> Mysql

Pivot dinamis 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

Ini versi dinamisnya

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. Database
  2.   
  3. Mysql
  4.   
  5. Oracle
  6.   
  7. Sqlserver
  8.   
  9. PostgreSQL
  10.   
  11. Access
  12.   
  13. SQLite
  14.   
  15. MariaDB
  1. PHP/MySQL - Menyimpan data array sebagai JSON, praktik buruk?

  2. Kapan harus mempertimbangkan Solr

  3. Akses ditolak untuk 'pengguna'@'localhost'

  4. Menggunakan MySql, dapatkah saya mengurutkan kolom tetapi 0 datang terakhir?

  5. Lihat hibah di MySQL