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

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

最佳答案

试试这个:

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;

fiddle :http://sqlfiddle.com/#!2/49c560/2

关于mysql - 查询到 mysql 数据库中的数据透视表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24715391/

相关文章:

php - 比较 2 个 MySQL 表的公共(public)字段,识别仅在其中 1 个表中的数据

php - 无法使用 docker compose 将 phpmyadmin 连接到数据库

mysql - SQL 正则表达式以错误的方式工作

mysql - MySQL 中的排名函数

sql - 如何展平 PostgreSQL 结果

php - 如何在 laravel 4 中使用数据透视表上的 where 条件来获取数据

php - 使用 PHP PDO 为每个 $_POST 插入行

PHP/MYSQL utf8 文件打开语法错误,但通过 phpmyadmin 工作正常

SQL 递归 CTE 返回的结果比预期多

mysql - MySQL 中 GROUP_CONCAT 的对立面是什么?