0
------------------------------------------------------------
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;
Ullas
  • 11,450
  • 4
  • 33
  • 50

1 Answers1

0

Query

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

Ullas
  • 11,450
  • 4
  • 33
  • 50