我有一个包含
的表names | grades | ages
我按等级排序,这是查询:
select * from students order by grades
我想将他们按百分比分成三组,第一组按学生人数的35%分组,其余两组依此类推
Group1 35%
group2 35%
group3 30%
我如何划分他们,因为划分是根据学生人数和这些条件而定的:
这是学生名单
names | Ages | Grades|
________________________
1 john | 30 | 20 |
2 saur | 24 | 15 |
3 laban | 22 | 20 |
4 steve | 26 | 16 |
5 sophie| 27 | 20 |
6 barry | 32 | 16 |
7 kevin | 31 | 19 |
8 jenny | 34 | 16 |
第1组= 8 * 35%/100=2.8,我带2个学生
第2组= 8 * 35%/100=2.8,我带2个学生
第3组= 8 * 30%/100=2.4,我带2个学生
这是我的尝试
with tt1 as
( select id,names,grades,datediff(Year,Bdate,current_date) as
ages from students
),
tt2 as
(
select id,names,grades,
case when ages >= 22 and ages < 99 then 1 else 0 end as group1,
case when ages >= 25 and ages < 99 then 1 else 0 end as group2,
case when ages >= 30 and ages < 99 then 1 else 0 end as group3,
from tt1 order by grades desc )
select * from tt2
这里的学生人数变为5。如何在SQL中做到这一点?当我按年级,年龄对其进行排序并按百分比进行划分时,会得到以下结果:
names | Ages | Grades|
________________________
1 john | 30 | 20 |
2 sophie| 27 | 20 |
3 laban | 22 | 20 |
4 kevin | 31 | 19 |
5 jenny | 34 | 16 |
6 barry | 32 | 16 |
7 steve | 26 | 16 |
8 saur | 24 | 15 |
8 students *35% =2.8 this is group1 = John,sophie
group2= kevin,jenny
group3= barry
我只有5个达到条件的学生。
我除以5。
5*35%=1.75 so group1 = 1 student
5*35%=1.75 so group2 = 1 student
5*30%=1.5 so group3 = 1 student
最终结果将是
names | Ages | Grades| Groups
_______________________________
1 john | 30 | 20 | 1
2 sophie| 27 | 20 | 2
3 kevin | 31 | 19 | 3