这种类型的数据变换为枢轴。在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 with Demo
均可以得到结果:
| NAME | OCCURRENCES_UK | OCCURRENCES_US | TOTAL_OCURRENCES |
-------------------------------------------------------------
| John | 3 | 4 | 7 |
| Matt | 0 | 5 | 5 |
如果国家的名单是未知的,你可以使用预处理语句和存储过程的组合来做到这一点,但坦率地说,做一个简单的GROUP BY并处理应用程序级别的显示会更容易。 – Strawberry
一群人会给每个s_name只有一行...我会失去每个国家的价值观,对吧? –