有兩種方法,你可以在樞軸數據在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