不幸的是,MySQL 没有一个UNPIVOT
orPIVOT
函数,但是可以使用UNION ALL
forUNPIVOT
和一个聚合函数来复制它们,并CASE
使用PIVOT
. 如果您知道要转换的值,则可以硬编码,然后类似于以下内容:
select col code,
sum(case when code = 'xxxx' then value end) xxxx,
sum(case when code = 'xxxx' then value end) yyyy
from
(
select code, A value, 'A' col
from table1
union all
select code, B value, 'B' col
from table1
) x
group by col;
请参阅带有演示的 SQL Fiddle
但是您说您将拥有未知数量的code
值。如果是这种情况,那么您可以pivot
对数据使用准备好的语句:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'SUM(case when code = ''',
code,
''' then value end) AS ',
code
)
) INTO @sql
FROM Table1;
SET @sql = CONCAT('SELECT col as code, ', @sql, '
FROM
(
select code, A value, ''A'' col
from table1
union all
select code, B value, ''B'' col
from table1
) x
GROUP BY col');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
请参阅SQL Fiddle with Demo。
两者都产生相同的结果:
| CODE | XXXX | YYYY |
----------------------
| A | 50 | 38 |
| B | 63 | 68 |