有两种方法可以在 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
如果您想使用带有准备好的语句的动态版本,代码将是:
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,在考虑到这一点之后,我实际上会稍微有点不同。我会生成一个真正的矩阵 os 数据,其中团队出现在行和列中。为此,您将首先使用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 |