在 SQL 中实现行列转置可以通过使用 CASE WHEN 结构来实现。以下是一个示例代码:
假设有一个表格 original_table
包含以下数据:
id | col1 | col2 | col3 |
---|---|---|---|
1 | A | B | C |
2 | D | E | F |
要将该表格的列转置为行,可以使用以下 SQL 语句:
SELECT
'col1' AS column_name,
MAX(CASE WHEN id = 1 THEN col1 END) AS row1,
MAX(CASE WHEN id = 2 THEN col1 END) AS row2
FROM original_table
UNION ALL
SELECT
'col2' AS column_name,
MAX(CASE WHEN id = 1 THEN col2 END) AS row1,
MAX(CASE WHEN id = 2 THEN col2 END) AS row2
FROM original_table
UNION ALL
SELECT
'col3' AS column_name,
MAX(CASE WHEN id = 1 THEN col3 END) AS row1,
MAX(CASE WHEN id = 2 THEN col3 END) AS row2
FROM original_table;
以上 SQL 语句将会将原始表格的列转置为行,生成如下结果:
column_name | row1 | row2 |
---|---|---|
col1 | A | D |
col2 | B | E |
col3 | C | F |