------------------------------------------------------------ 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/