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

在数据库分组查询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
);

转载请

注明出处
 

猜你喜欢

转载自blog.csdn.net/cherishpart/article/details/49997285