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

Seleziona i valori di riga dinamici come nomi di colonna, in un ordine specifico

Puoi farlo aggiungendo ORDER BY start_time ASC nel tuo GROUP_CONCAT funzione

SET @sql = NULL;

SELECT GROUP_CONCAT(DISTINCT
  CONCAT('MAX(CASE WHEN job_id = ''',
         job_id, 
         ''' THEN start_time END) `',
         job_id,
         '_start`',
         ',',
         'MAX(CASE WHEN job_id = ''',
         job_id,
         ''' THEN end_time END) `',
         job_id,
         '_end`' 
         )
          ORDER BY start_time ASC        
 )
  INTO @sql
  FROM t;

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

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

Fiddle Demo