MySQL dynamic-pivot

天涯浪子 提交于 2019-11-26 14:45:27

Unfortunately, MySQL does not have a PIVOT function but you can model it using an aggregate function and a CASE statement. For a dynamic version, you will need to use prepared statements:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when part_type = ''',
      part_type,
      ''' then part_id end) AS part_',
      part_type, '_id'
    )
  ) INTO @sql
FROM
  parts;
SET @sql = CONCAT('SELECT product_id, ', @sql, ' 
                  FROM parts 
                   GROUP BY product_id');

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

See SQL Fiddle With Demo

If you had only a few columns, then you can use a Static version:

select product_id,
  max(case when part_type ='A' then part_id end) as Part_A_Id,
  max(case when part_type ='B' then part_id end) as Part_B_Id
from parts
group by product_id
PeteGO

SQL Server has a PIVOT keyword, but with MySQL you will need to use either a lot of CASE/IF statements or a lot of JOINs.

Here is a previous post of how to do this.

just reference it twice - (you don't really have much of a question here)

select a.product_id, a.part_id "part_a_id", b.part_id "part_b_id"
from parts a, parts b
where a.product_id = b.product_id
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!