Mysql 行转列 和 列转行

579 阅读1分钟

1. 行转列

首先上图,对于这样的表结构,如何输出这样的结果

表结构和数据:

想要输出这样的结果:

这就是经典的行转列问题。

方案一:
select distinct a.name ,
(select score from score_table b where a.name = b.name and b.subject = '语文') as '语文',
(select score from score_table b where a.name = b.name and b.subject = '数学') as '数学',
(select score from score_table b where a.name = b.name and b.subject = '英语') as '英语'
from score_table a

使用表连接输出了想要的结果。

我们还可以使用case when来处理:

方案二:
select name,
max((CASE subject
	WHEN '语文' THEN
		score
	ELSE
		0
END)) as '语文',
max((CASE subject
	WHEN '数学' THEN
		score
	ELSE
		0
END)) as '数学',
max((CASE subject
	WHEN '英语' THEN
		score
	ELSE
		0
END)) as '英语'
from score_table
group by name

这里用了case when 搭配分组函数和max 函数来处理。

2. 列转行

其实就是行转列的反转, 已有现在的表结构和数据,

想要实现这样的结果:

方案:
select name, '语文' as subject, 语文 as score from score_table_copy 
union
select name, '数学' as subject, 数学 as score from score_table_copy 
union
select name, '英语' as subject, 英语 as score from score_table_copy 
order by name

搞定!