mysql-结合了数据透视表,计数,组,联合,频率,联接和顺序的复杂查询

时间:2018-08-28 07:31:42

标签: mysql count pivot-table union frequency-distribution

我有下表,其中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 | 

2 个答案:

答案 0 :(得分:1)

在以下情况下使用案例:

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

答案 1 :(得分:1)

您可以使用按年龄分组的select case和sum()进行选择性汇总

    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