有两种方法,你可以在枢轴数据在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 |
它不会是太难的事它的五支球队的具体情况,但是这将扩展到任意数量的团队和游戏的一个通用的解决方案将是相当棘手单独使用sql。 – paul 2013-02-08 12:48:32
数据库用于存放和获取数据,**不**可以很好地格式化数据。这是在表示层完成的! – fancyPants 2013-02-08 12:59:49
@Megachip。 。 。这两个都是矩阵。他们只是代表不同。 – 2013-02-08 14:02:53