我在表中有这样的数据:
=================================
name | study | avg_scores
=================================
alfa c# 75
beta c# 70
alfa php 85
beta php 90
我想要这样的结果:
===========================
name | c# | php
===========================
alfa 75 85
beta 70 90
那么如何在 mysql 中进行查询以获得这些结果呢? 谢谢:)
最佳答案
试试这个:
select first.name,
max(if(first.study = 'c#', first.avg_scores, NULL)) as 'c#',
max(if(first.study = 'php', first.avg_scores, NULL)) as php
from `table` first
join `table` second
on first.name = second.name
group by first.name
fiddle :http://sqlfiddle.com/#!2/3c61c/1
对于动态的:
set @sql = NULL;
select
group_concat(distinct
concat(
'max(if(first.study = ''',
study, ''', first.avg_scores, NULL)) as ',
study
)
) into @sql
from `table`;
SET @sql = concat('select first.name,
', @sql, '
from `table` first
join `table` second
on first.name = second.name
group by first.name');
prepare stmt from @sql;
execute stmt;
deallocate prepare stmt;
关于mysql - 查询到 mysql 数据库中的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24715391/