这种类型的数据转换是一个枢纽。在 MySQL 中,要生成此结果,您将使用带有case
表达式的聚合函数:
select name,
sum(case when country_id = 'uk' then n_ocurrences else 0 end) occurrences_uk,
sum(case when country_id = 'us' then n_ocurrences else 0 end) occurrences_us,
sum(n_ocurrences) total_ocurrences
from yourtable
group by name
请参阅SQL Fiddle with Demo。
country_id
如果您提前知道 的值,则上述版本效果很好,但如果您不知道,则可以使用准备好的语句来生成动态 sql:
SET @sql = NULL;
SELECT
GROUP_CONCAT(DISTINCT
CONCAT(
'sum(case when country_id = ''',
country_id,
''' then n_ocurrences end) AS occurrences_',
country_id
)
) INTO @sql
FROM yourtable;
SET @sql = CONCAT('SELECT name, ', @sql, ' ,
sum(n_ocurrences) total_ocurrences
FROM yourtable
GROUP BY name');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
请参阅带有演示的 SQL Fiddle
两者都给出结果:
| NAME | OCCURRENCES_UK | OCCURRENCES_US | TOTAL_OCURRENCES |
-------------------------------------------------------------
| John | 3 | 4 | 7 |
| Matt | 0 | 5 | 5 |