在网上看到sql分组统计的例子,收藏学习.
|------------------------------------------------------------------------------------|
现有人口信息表,表中有字段年龄(整型),性别(字符)
要求统计不同年龄段的男女比例,形成如下表格
年龄 男 女
---------------------------
18以下
18-30
30-40
40-50
50-60
60以上
实现sql如下:
- select 年龄,sum(男),sum(女)
- from
- (
- select
- case when 年龄<18 then '18以下' else
- case when 年龄>=18 and 年龄<30 then '18-30' else
- case when 年龄>=30 and 年龄<40 then '30-40' else
- case when 年龄>=40 and 年龄<50 then '40-50' else
- case when 年龄>=50 and 年龄<60 then '50-60' else
- case when 年龄>=60 then '60以上'
- else '其他' end end end end end as 年龄,
- case when 性别='男' then 1 else 0 end as 男,
- case when 性别='女' then 1 else 0 end as 女
- from 人口信息表
- ) as T
- group by T.年龄
- order by T.年龄