转载

数据库行列转换

示例(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
----------------------------------------

方案1

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

方案2

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
原文  http://wubaoguo.com/2016/12/03/数据库/数据库行列转换/
正文到此结束
Loading...