sum(case when ... then end) 使用

来源:互联网 发布:查看oracle端口 编辑:程序博客网 时间:2024/05/21 11:36

统计国家性别人口

有如下数据
国家(country) 性别(sex) 人口(population)
中国 1 340
中国 2 260
美国 1 45
美国 2 55
加拿大 1 51
加拿大 2 49
英国 1 40
英国 2 60

按照国家和性别进行分组,得出结果如下
国家 男 女
中国 340 260
美国 45 55
加拿大 51 49
英国 40 60

SELECT    country,    sum(        CASE        WHEN sex = 1 THEN            population        END    ) as men,    sum(        CASE        WHEN sex = 2 THEN            population        END    ) as womenFROM    cGROUP BY    country

统计每个人及格和不及格的科目数目

a chinese 100
a math 90
a english 95
b chinese 90
b math 80
b english 100
c chinese 120
c math 70
c english 60

SELECT    a.name,    count(case when score > 90 then a.name end),    count(case when score <= 90 then a.name end)FROM    aINNER JOIN b on a.`subject` = b.`subject`group by a.name
0 0