数据库实现行列转换功能的步骤

数据库实现行列转换功能的步骤

这篇文章通过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

总结

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