结合pivot表、count、group、union、frequency、join和order的复杂查询

v8wbuo2f  于 2021-06-20  发布在  Mysql
关注(0)|答案(2)|浏览(394)

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

amrnrhlw1#

您可以使用基于按年龄分组的select case and 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
az31mfrm

az31mfrm2#

使用情形:

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

相关问题