Skip to content Skip to sidebar Skip to footer

Mysql - Dynamic Pivot Table Grouping Issue

I'm trying to create a dynamic pivot table using a MySQL Prepared Statement I've put together from the numerous other questions about MySQL pivot tables. But I'm not getting the ou

Solution 1:

The following SQL can be a starting point for solving the problem:

SELECT
  es.employee_id,
  CONCAT(e.first_name, " ", e.last_name) AS employee,
  MAX(IF (es.skill_id =1, es.date_trained, null)) AS'1',
  MAX(IF (es.skill_id =2, es.date_trained, null)) AS'2',
  MAX(IF (es.skill_id =3, es.date_trained, null)) AS'3'FROM
  employee_skills es
  LEFTJOIN employees e ON es.employee_id = e.id
GROUPBY
  es.employee_id 

Result is a pivot table like this:

| employee_id | employee   |1|2|3|+-------------+------------+------------+------------+------------+|1001675| Person Two | (null)     |2016-07-02|2016-07-04||1006111| Person One|2016-07-01|2016-07-11| (null)     |

If SQL is created dynamically the skill IDs can be replaced by the skill name. Also it is possible to replace the IDs afterwards.

Post a Comment for "Mysql - Dynamic Pivot Table Grouping Issue"