mysql - mysql中将行转换为列

标签 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   |

I want to convert it to something like this dynamically

---------------------------------
|course1 | course2   | course3  |
---------------------------------
 BSIT     | BSCS     | BSCS     |  

I have this code and giving me Result :

MySQL returned an empty result set (i.e. zero rows).

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'count(case when course = ''',
      course,
      ''' then 1 end) AS ',
      replace(course, ' ', '')
    )
  ) INTO @sql
from tbl_course;

SET @sql = CONCAT('SELECT course, ', @sql, ' from tbl_course

group by course');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

最佳答案

查询

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

关于mysql - mysql中将行转换为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46191178/

相关文章:

asp.net - 可扩展性案例研究

java - 如何将 SQLite 数据从 Android 发送到 MySQL 服务器?

php - 数据未插入我正在使用 php mysql

php - MYSQL SELECT 不返回某些结果

mysql - 选择分组值

mysql - 导入时更改 mysql 表存储引擎

mysql - 为电子商务创建数据库结构

MySQL:数据库中按日期聚合的总用户数

64 位 MySQL 的 PHP 年份 2038 问题无法通过 PHPMyAdmin 插入日期

MySQL 解释行数限制