MySql select dynamic row values as column names

前端 未结 2 1415
慢半拍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

    0 讨论(0)
  • 2020-12-21 22:24

    Yes, it's possible in MySQL, but with any SQL database, you can't make a query that dynamically creates columns from the data values it finds. Columns of a query must be fixed at the time you prepare the query. So you must know the distinct values you want to be columns beforehand. This may require another query. This is true in all SQL databases, not just MySQL.

    SELECT exec_id,
     MIN(CASE job_id WHEN 'init' start_time END) AS init_start,
     MIN(CASE job_id WHEN 'init' end_time END) AS init_end,
     MIN(CASE job_id WHEN 'job_id_1' start_time END) AS job_id_1_start,
     MIN(CASE job_id WHEN 'job_id_1' end_time END) AS job_id_1_end
    FROM `this_is_my_given_table`
    GROUP BY exec_id
    

    This basically hard-codes each distinct job id, but that's necessary.

    0 讨论(0)
提交回复
热议问题