mysql 行变列(多行变成一行/多行合并成一行/多行合并成多列/合并行)

数据库结构如图:

而我想让同一个人的不同成绩变成此人在这一行不同列上显示出来,此时分为2中展现:

第一种展现如图----【多行变一列】(合并后的数据在同一列上):

sql如下:

 

select name ,group_concat(sore Separator ';') as score from stu group by name 

第二种展现如图----【多行变多列】(合并后的数据在不同列上):

 

sql如下:

 

SELECT name ,
MAX(CASE type WHEN '数学' THEN score ELSE 0 END ) math,
MAX(CASE type WHEN '英语' THEN score ELSE 0 END ) English ,
MAX(CASE type WHEN '语文' THEN score ELSE 0 END ) Chinese 
FROM stu  
GROUP BY name

-----------------------------------------------------------------------------------------------------可爱的分割线----------------------------------------------------------------------------------------------------

 

当然,在第一种情况中(显示在一列),也有些其他的类似形式:

形式一:

sql如下:

 

select name ,group_concat(type,'分数为:',score  Separator '; ') as score from stu group by name 


呵呵,当然 如果你很熟悉group_concat和concat的用法,你也做出如下形式:

 

其sql如下:

 

select name ,concat(name ,'的分数为[',group_concat(type,'分数为:',score  Separator '; '),']') as score from stu group by name 

posted on 2016-11-26 22:22  很丑怎么温柔  阅读(11491)  评论(1编辑  收藏  举报

导航