在MySQL中,可以使用以下方法將行轉列:
SELECT
id,
MAX(CASE WHEN type = 'A' THEN value END) AS value_a,
MAX(CASE WHEN type = 'B' THEN value END) AS value_b,
MAX(CASE WHEN type = 'C' THEN value END) AS value_c
FROM table_name
GROUP BY id;
SELECT
t1.id,
t2.value AS value_a,
t3.value AS value_b,
t4.value AS value_c
FROM table_name t1
JOIN table_name t2 ON t1.id = t2.id AND t2.type = 'A'
JOIN table_name t3 ON t1.id = t3.id AND t3.type = 'B'
JOIN table_name t4 ON t1.id = t4.id AND t4.type = 'C';
SELECT
id,
SUBSTRING_INDEX(GROUP_CONCAT(CASE WHEN type = 'A' THEN value END), ',', 1) AS value_a,
SUBSTRING_INDEX(GROUP_CONCAT(CASE WHEN type = 'B' THEN value END), ',', 1) AS value_b,
SUBSTRING_INDEX(GROUP_CONCAT(CASE WHEN type = 'C' THEN value END), ',', 1) AS value_c
FROM table_name
GROUP BY id;
這些方法可以根據具體的需求選擇適合的方式來將行轉列。