使用 MySQL 的聚合函数和 CASE 语句动态地转换数据
考虑具有以下架构的产品部件表:
CREATE TABLE Parts ( part_id INT NOT NULL, part_type CHAR(1) NOT NULL, product_id INT NOT NULL, PRIMARY KEY (part_id) );
示例数据:
INSERT INTO Parts (part_id, part_type, product_id) VALUES (1, 'A', 1), (2, 'B', 1), (3, 'A', 2), (4, 'B', 2), (5, 'A', 3), (6, 'B', 3);
目标是将这些数据转换为将产品部件表示为列的表:
CREATE TABLE PivotedParts ( product_id INT NOT NULL, part_A_id INT, part_B_id INT, PRIMARY KEY (product_id) );
动态透视解决方案:
MySQL没有内置的PIVOT函数,但是可以使用聚合函数和a来实现动态解决方案CASE 语句:
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;
示例输出:
+------------+----------+----------+ | product_id | part_A_id | part_B_id | +------------+----------+----------+ | 1 | 1 | 2 | | 2 | 3 | 4 | | 3 | 5 | 6 | +------------+----------+----------+
静态旋转解决方案(对于有限数量的列):
对于列数有限的静态透视解决方案,可以使用以下查询使用:
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;
输出:
+------------+----------+----------+ | product_id | part_A_id | part_B_id | +------------+----------+----------+ | 1 | 1 | 2 | | 2 | 3 | 4 | | 3 | 5 | 6 | +------------+----------+----------+
以上是如何使用聚合函数和 CASE 语句动态透视 MySQL 中的数据?的详细内容。更多信息请关注PHP中文网其他相关文章!