這篇文章通過sql示例代碼給大家介紹了mysql數(shù)據(jù)庫如何實(shí)現(xiàn)行列轉(zhuǎn)換,下面話不多說,直接來看示例代碼吧。
原表:
表名 :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
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能有一定的幫助,如果有疑問大家可以留言交流。
您可能感興趣的文章:- mysql 行列動(dòng)態(tài)轉(zhuǎn)換的實(shí)現(xiàn)(列聯(lián)表,交叉表)
- mysql 行列轉(zhuǎn)換的示例代碼