在mysql中将行转换为列

时间:2017-09-13 07:16:21

标签: mysql

------------------------------------------------------------
courseid|course    |coursedesc                             |
------------------------------------------------------------
 1      | BSIT     |  Bachelor of science in info tech     |
 2      | BSCS     |   Bachelor of science in comp sci     |
 3      | BSHRM    |  Bachelor of science in hotel & res   |

我想将其转换为类似动态

的内容
---------------------------------
|course1 | course2   | course3  |
---------------------------------
 BSIT     | BSCS     | BSCS     |  

我有这个代码并给我结果:

MySQL返回一个空结果集(即零行)。

matplotlib==2.0.2

1 个答案:

答案 0 :(得分:0)

<强>查询

set @query = null;
select
  group_concat(distinct
    concat(
      'max(case when `courseid` = ',
      `courseid`, ' then `course` end) as `course', `courseid`, '`'
    )
  ) into @query
from `tbl_course`;

set @query = concat('select ', @query, ' from `tbl_course` ');

prepare stmt from @query;
execute stmt;
deallocate prepare stmt;

<强> Find a demo here