MySql select dynamic row values as column names

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

This is my given table:

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


        
2条回答
  •  余生分开走
    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.

提交回复
热议问题