MySql select dynamic row values as column names

前端 未结 2 1421
慢半拍i
慢半拍i 2020-12-21 21:48

This is my given table:

+---------+------------+-------------------+--------------------------+---------------+---------------+
| exec_id | project_id | flow_         


        
2条回答
  •  半阙折子戏
    2020-12-21 22:19

    As from reference question's approach of using group_concat you can do so,but note one thing as your job ids increases per exec_id group then group_concat approach will not be optimal due to its default length of 1024 characters to concatenate and for your dynamic columns this will surely cross that limit,but this limit can be increased as mentioned in documentation

    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`' 
             )
    
     )
      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

提交回复
热议问题