Mysql
 sql >> Base de données >  >> RDS >> Mysql

Transposer les lignes aux en-têtes dans MYSQL

Voici un sql dynamique pour faire pivoter les enregistrements,

SET @sql = NULL;

SELECT  GROUP_CONCAT(DISTINCT
        CONCAT('MAX(CASE WHEN date = ''',
               date,
               ''' THEN Value ELSE NULL END) AS ',
               CONCAT('`', date, '`')
               )) INTO @sql
FROM TableName
// WHERE date >= curdate() - interval 3 day  // add condition here
ORDER BY date;



SET @sql = CONCAT('SELECT ', @sql, ' 
                   FROM TableName');

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