您的位置:首页 > 数据库 > Oracle

Oracle数据库之group by:按自定规则分组

2015-11-23 16:36 435 查看
在数据库分组查询group by 中,默认的方式有按某一个字段的均分查询(如按班级编号分组,每一个班分组,每两个班分组。。。)

在这里写出一种按照自定义规则分组的方式:

以下语句,按自定义的格式将大于等于18个班级的学生分为4类,统计每个类别的学生数量。当然,同类未必要班级号相连,分类条件写在when ...then之间 then之后的标志作为分类名称。

create table student
(
xh varchar2(10) primary key,
class_no number(6) not null
);
select
case
when class_no>=1 and class_no<=2 then 1
when class_no>=3 and class_no<=6 then 2
when class_no>=7 and class_no<=17 then 3
when class_no>=18 then 4
end
as class_fenlei,--班级分类
count(xh)--每个班级分类的学生人数
from student
group by (
case
when class_no>=1 and class_no<=2 then 1
when class_no>=3 and class_no<=6 then 2
when class_no>=7 and class_no<=17 then 3
when class_no>=18 then 4
end
);


请勿转载

------------------------------------------------------------------------我是萌萌的小尾巴,Sherlock Law
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息