mysql - SQL 语句 - SQL 矩阵

标签 mysql sql pivot

对于下表,是否可以创建 SQL 语句来创建数据矩阵或 View ?

表:

TeamA|TeamB|Won|Lost
--------------------
  A  |  B  | 5 | 3
  A  |  C  | 2 | 4
  A  |  D  | 9 | 1
  B  |  E  | 5 | 5
  C  |  A  | 2 | 4

结果矩阵:

     |  A | B |  C | D | E
----------------------------
  A  |  0 | 2 | -2 | 8 | 0
  B  |  0 | 0 |  0 | 0 | 0
  C  | -2 | 0 |  0 | 0 | 0

最佳答案

有两种方法可以在 MySQL 中透视数据。如果您提前知道这些值(团队),那么您将对这些值进行硬编码,或者您可以使用准备好的语句来生成动态 sql。

静态版本是:

select TeamA,
  max(case when TeamB = 'A' then won - lost else 0 end) as A,
  max(case when TeamB = 'B' then won - lost else 0 end) as B,
  max(case when TeamB = 'C' then won - lost else 0 end) as C,
  max(case when TeamB = 'D' then won - lost else 0 end) as D,
  max(case when TeamB = 'E' then won - lost else 0 end) as E
from yourtable
group by TeamA;

参见SQL Fiddle with Demo

如果您想使用带有准备好的语句的动态版本,代码将为:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN TeamB = ''',
      TeamB,
      ''' THEN won - lost else 0 END) AS `',
      TeamB, '`'
    )
  ) INTO @sql
from
(
  select *
  from yourtable
  order by teamb
) x;

SET @sql 
  = CONCAT('SELECT TeamA, ', @sql, ' 
           from yourtable
           group by TeamA');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

参见SQL Fiddle with Demo .

编辑#1,考虑到这一点后,我实际上会做一些稍微不同的事情。我将生成一个真实的矩阵,其中团队出现在行和列中。为此,您首先需要使用 UNION ALL 查询来获取两列中的所有团队:

select teama Team1, teamb Team2,
  won-lost Total
from yourtable
union all
select teamb, teama,
  won-lost
from yourtable

参见SQL Fiddle with Demo 。完成后,您将透视数据:

select Team1,
  coalesce(max(case when Team2 = 'A' then Total end), 0) as A,
  coalesce(max(case when Team2 = 'B' then Total end), 0) as B,
  coalesce(max(case when Team2 = 'C' then Total end), 0) as C,
  coalesce(max(case when Team2 = 'D' then Total end), 0) as D,
  coalesce(max(case when Team2 = 'E' then Total end), 0) as E
from
(
  select teama Team1, teamb Team2,
    won-lost Total
  from yourtable
  union all
  select teamb, teama,
    won-lost
  from yourtable
) src
group by Team1;

参见SQL Fiddle with Demo 。这给出了更详细的结果:

| TEAM1 |  A | B |  C | D | E |
-------------------------------
|     A |  0 | 2 | -2 | 8 | 0 |
|     B |  2 | 0 |  0 | 0 | 0 |
|     C | -2 | 0 |  0 | 0 | 0 |
|     D |  8 | 0 |  0 | 0 | 0 |
|     E |  0 | 0 |  0 | 0 | 0 |

关于mysql - SQL 语句 - SQL 矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14772882/

相关文章:

sql - 查询表的外键关系

sql 包不执行 printf

sql-server - 具有联接和动态列的 SQL SERVER PIVOT 表

php - MySQL NOT LIKE 查询不工作

java - 不同方法中的类似 SQL 查询

sql - 透视带有文本且无聚合的表

sql - 如何将选择查询结果插入 PIVOT

来自不同数据库的 Mysqldump 表?

mysql - 显示和清除数据库中标签中的值

mysql - 将 MyISAM 表迁移到实时站点上的 InnoDB