Der er to måder, du kan pivotere på data i MySQL. Hvis du kender værdierne i forvejen (hold), vil du hårdkode værdierne, eller du kan bruge en forberedt erklæring til at generere dynamisk sql.
En statisk version ville være:
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;
Hvis du ønsker at bruge en dynamisk version med en forberedt sætning, vil koden være:
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;
Se SQL Fiddle with Demo .
Rediger #1, efter at have tænkt over dette ville jeg faktisk gøre det en smule anderledes. Jeg ville generere en sand matrix for de data, hvor holdene optrådte i både rækken og kolonnen. For at gøre dette skal du først bruge en UNION ALL
forespørgsel for at få alle hold i to kolonner:
select teama Team1, teamb Team2,
won-lost Total
from yourtable
union all
select teamb, teama,
won-lost
from yourtable
Se SQL Fiddle with Demo . Når det er gjort, vil du pivotere dataene:
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;
Se SQL Fiddle with Demo . Hvilket giver et mere detaljeret resultat af:
| 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 |