1.多行转多列
行列转换就是如下图所示两种展示形式的互相转换
(1)使用PIVOT函数
SELECT * FROM student PIVOT ( SUM(score) FOR subject IN (语文, 数学, 英语) ) #默认按照score和subject以外其它字段进行group by
(2)使用Case When
结果跟上述函数一致,但是当涉及字段较多时,使用case when书写可能不太直观。
SELECT name, MAX( CASE WHEN subject='语文' THEN score ELSE 0 END) AS "语文", MAX( CASE WHEN subject='数学' THEN score ELSE 0 END) AS "数学", MAX( CASE WHEN subject='英语' THEN score ELSE 0 END) AS "英语" FROM student GROUP BY name
2.多列转多行
(1)使用UNPIVOT函数
SELECT * FROM student1 UNPIVOT ( score FOR subject IN ("语文","数学","英语") )
(2)使用Case When
结果跟上述函数一致,但是当涉及字段较多时,使用case when书写可能不太直观。
SELECT NAME, '语文' AS subject , MAX("语文") AS score FROM student1 GROUP BY NAME UNION SELECT NAME, '数学' AS subject , MAX("数学") AS score FROM student1 GROUP BY NAME UNION SELECT NAME, '英语' AS subject , MAX("英语") AS score FROM student1 GROUP BY NAME
3.多行转一列
参考文档: