这篇文章通过sql示例代码给大家介绍了mysql数据库如何实现行列转换,下面话不多说,直接来看示例代码吧。

原表:

表名 :user
----------------------------------------
name    | course  | grade
----------------------------------------
zhangsan  | Java   | 70
----------------------------------------
zhangsan  | C++   | 80
----------------------------------------
lisi    | java   | 90
----------------------------------------
lisi    | C#    | 60
----------------------------------------

用一条 SQL 语句得到如下形式:

----------------------------------------
name   | java | C++ | C#
----------------------------------------
zhangsan | 70  | 80  | null
----------------------------------------
lisi   | 90  | null | 60
----------------------------------------

方案一

select  name,
sum(case when course='java' then grade end) as java,
sum(case when course='C++' then grade end) as C++,
sum(case when course='C#' then grade end) as C#
from test group by name

方案二

select distinct c.`name` AS name,
(select grade from test where name = c.`name` and course = 'java' )as java,
(select grade from test where name = c.`name` and course = 'C++' )as C++,
(select grade from test where name = c.`name` and course = 'C#' )as C#
from test c

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能有一定的帮助,如果有疑问大家可以留言交流。

华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com