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.年龄
|------------------------------------------------------------------------------------|
现有人口信息表,表中有字段年龄(整型),性别(字符)
要求统计不同年龄段的男女比例,形成如下表格
年龄 男 女
---------------------------
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.年龄
相关文章推荐
- sql 分组统计的例子
- 一个sql例子,分组,查询,统计等操作,老忘记,记录一下
- [转载] SQL进行排序、分组、统计的10个新技巧
- 关于SQL分组统计
- Oracle按时间分组统计的sql与oracle 多行合并一行
- SQL进行排序、分组、统计的10个新技巧
- sq更新语句条件子查询中有分组统计的sql,导致错误1093
- my sql-关于sql模糊分组统计
- 数据统计例子,相关子查询!(SQL 中循环操作一列数据方法)
- SQL 分组统计之------汇总乘积
- SQL脚本去重分组统计
- MongoDB分组统计的一个例子
- oracle分组统计sql
- SQL进行排序、分组、统计的10个新技巧
- 用Sql语句怎么 将分组查询得到的记录数 统计出来
- SQL实现分组统计查询(按月、小时分组)
- sql server数据分组统计
- sql GROUP BY 分组统计
- SQL数据进行排序、分组、统计10技巧
- SQL 统计分组 Group By和Compute By的整理