MySQL---行转列
Posted Shall潇
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了MySQL---行转列相关的知识,希望对你有一定的参考价值。
mysql—行转列
一、行转列
1、SqlServer和Orcle中可以使用pivot行转列函数快速实现,而MySQL中没有
pivot:
SELECT *
FROM student
PIVOT (
SUM(score) FOR subject IN (语文, 数学, 英语)
)
2、MySQL实现行转列
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
二、列转行
unpivot
1、其他转换
SELECT *
FROM student1
UNPIVOT (
score FOR subject IN ("语文","数学","英语")
)
2、MySQL转换
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
开发者涨薪指南
48位大咖的思考法则、工作方式、逻辑体系
以上是关于MySQL---行转列的主要内容,如果未能解决你的问题,请参考以下文章