在SQL中进行行列互换可以使用PIVOT函数。下面是一个示例查询及其对应的结果:
- 创建测试表格
sql
CREATE TABLE test_table (
id INT PRIMARY KEY,
name VARCHAR(50),
category VARCHAR(50)
);
- 向测试表格插入数据
sql
INSERT INTO test_table VALUES (1, 'A', 'Category A');
INSERT INTO test_table VALUES (2, 'B', 'Category B');
INSERT INTO test_table VALUES (3, 'C', 'Category C');
INSERT INTO test_table VALUES (4, 'D', 'Category D');
INSERT INTO test_table VALUES (5, 'E', 'Category E');
- 使用PIVOT函数进行行列互换
sql
SELECT * FROM (
SELECT id, name, category
FROM test_table
) AS src
PIVOT (
MAX(name) FOR category IN ([Category A], [Category B], [Category C], [Category D], [Category E])
) AS piv;
运行上述查询后,将会得到如下结果: