您的位置:首页 > 数据库

sql 分组统计的例子【转】

2012-02-10 13:53 459 查看
在网上看到sql分组统计的例子,收藏学习.

|------------------------------------------------------------------------------------|

现有人口信息表,表中有字段年龄(整型),性别(字符)
要求统计不同年龄段的男女比例,形成如下表格

年龄 男 女
---------------------------
18以下
18-30
30-40
40-50
50-60
60以上

实现sql如下:

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.年龄
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: