使用 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中文網其他相關文章!