MySQL中的动态交叉制表符

时间:2012-08-16 06:38:15

标签: mysql sql

我的下表包含以下数据


Year | Age Group | Male | Female
2000 | 0 - 25    | 50   | 100
2000 | 26 above  | 40   | 75
2001 | 0 - 25    | 150  | 86
2001 | 26 above  | 65   | 83

我想以下列格式创建一个交叉表

                |  Male   | Female
2000            |  90     | 175
       0 - 25   |  50     | 100
       26 above |  40     | 75
2001            |  215    | 169
       0 - 25   |  150    | 86
       26 above |  65     | 83

我将非常感谢你的帮助。

1 个答案:

答案 0 :(得分:3)

SQLFiddle example

select * from
(
select year,ageGroup,male,female from t
union all
select year,'' ageGroup,sum(male) male,sum(female) female 
from t group by year
) st
order by year,agegroup