By
wustrive
更新日期:
文章目录
示例(mysql)
原表:
1 2 3 4 5 6 7 8 9 10 11 12
| 表名 :user ---------------------------------------- name | course | grade ---------------------------------------- zhangsan | Java | 70 ---------------------------------------- zhangsan | C++ | 80 ---------------------------------------- lisi | java | 90 ---------------------------------------- lisi | C# | 60 ----------------------------------------
|
用一条 SQL 语句得到如下形式:
1 2 3 4 5 6 7
| ---------------------------------------- name | java | C++ | C# ---------------------------------------- zhangsan | 70 | 80 | null ---------------------------------------- lisi | 90 | null | 60 ----------------------------------------
|
方案1
1 2 3 4 5
| 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
1 2 3 4 5
| 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
|