查询到mysql数据库中的数据透视

时间:2014-07-12 17:11:44

标签: mysql sql pivot

我在表格中有这样的数据:

=================================
  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中进行查询以获得这些结果呢? 谢谢:))

2 个答案:

答案 0 :(得分:1)

试试这个:

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

小提琴: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;

小提琴:http://sqlfiddle.com/#!2/49c560/2

答案 1 :(得分:0)

您的查询将是:

select n.name, c.avg_scores as C_AVG, p.avg_scores as PHP_AVG from `table` n join `table` c on n.name=c.name and c.study="c#" join `table` p on n.name=p.name and p.study="php" group by n.name

更新:如果研究类型无关紧要,请尝试以下方法:

select name, study, avg_scores from `table` group by name, study 

如果不按列返回,但它运行良好。