这基本上是一个PIVOT
但 MySQL 没有函数,因此您可以使用带有聚合函数的语句PIVOT
来复制它。CASE
如果您有已知数量的type
值,则可以对这些值进行硬编码:
select year,
avg(case when type='A' then price end) PriceA,
avg(case when type='B' then price end) PriceB
from yourtable
group by year
请参阅带有演示的 SQL Fiddle
结果:
| YEAR | PRICEA | PRICEB |
--------------------------
| 1999 | (null) | 100 |
| 2002 | 200 | 120 |
| 2004 | 202 | (null) |
| 2005 | 206 | (null) |
如果您的数量未知,types
则可以使用准备好的语句:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'avg(case when type = ''',
type,
''' then price end) AS Price',
type
)
) INTO @sql
FROM yourtable;
SET @sql = CONCAT('SELECT year, ', @sql, '
FROM yourtable
GROUP BY year');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
请参阅带有演示的 SQL Fiddle