這篇文章通過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
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能有一定的幫助,如果有疑問大家可以留言交流。