mysql - 结合主元 table、计数、组、联合、频率、连接和顺序的复杂查询

mysql - complex query combining pivot table, count, group, union, frequency, join and order

我有以下 table 其中 a1 是可以重复的年龄。 g1 是性别,其中 0 表示男性,1 表示女性。

| a1 | g1|    
.................    
|   40 |   0 |    
|   48 |   1 |      
|   47 |   0 | 
|   52 |   0 |       
|   64 |   1 |      
|   50 |   1 |     
|   63 |   1 |     
|   57 |   0 |  

我想用每行男女总和来显示按年龄划分的男女人数。我无法得到想要的结果。

| a1 |male|female|total|    
-----------------------------
| 40 | 120 | 80 | 200 |     
| 48 | 130 | 90 | 220 |     
| 47 | 140 | 70 | 210 |      
| 52 | 150 | 40 | 190 |     
| 64 | 160 | 45 | 205 |     
| 50 | 170 | 30 | 200 |     
| 63 | 180 | 30 | 210 |     
| 57 | 190 | 50 | 240 | 

使用案例:

select a1 as age, sum(case when g1=0 then 1 end) as male, sum(case when g1=1 then 1 end) as female, sum(case when g1 in (1,0) then 1 end) as total
group by a1

您可以使用 select case 和基于年龄组的 sum() 进行 selective 聚合

    SELECT  a1 age 
        , SUM(CASE WHEN g1=0 THEN 1 END)  male
        , sum(CASE WHEN g1=1 THEN 1 END)  female
        , SUM(CASE WHEN g1=0 THEN 1 END)  +sum(CASE when g1=1 THEN 1 END)  total
    FROM my_table
    GROUP BY a1