在MySQL中,行列交换可以通过使用UNION ALL和CASE语句来实现。假设我们有以下表:
+------+------+------+
| id | name | score|
+------+------+------+
| 1 | Tom | 80 |
| 2 | Jack | 90 |
| 3 | Lucy | 85 |
+------+------+------+
要将行列进行交换,即将每个姓名作为列名,每个分数作为值,并将id排除在结果之外,可以使用以下查询:
SELECT 'Tom' AS name,
MAX(CASE WHEN id = 1 THEN score ELSE NULL END) AS Tom,
'Jack' AS name,
MAX(CASE WHEN id = 2 THEN score ELSE NULL END) AS Jack,
'Lucy' AS name,
MAX(CASE WHEN id = 3 THEN score ELSE NULL END) AS Lucy
FROM table_name;
输出结果如下:
+------+-----+------+-----+------+------+
| name | Tom | Jack | Lucy| Tom |Jack |
+------+-----+------+-----+------+------+
| Tom | 80 |null |null |null |null |
| Jack |null | 90|null |null |null
| Lucy |null |null 85 null null
+------+-----+------+-----+------+-------+
注意,在以上查询中,我们首先指定了每个姓名作为一个新的列名,并使用了MAX函数将行转换为列。