这是您可以采取的方法。
关键思想是计算每个班级的男女学生人数,然后分配他们。任务很简单,如果我们有信息的话。所以,假设我们有它:
with magictable (
<subquery here is nummale and numfemale in each class
),
classinfo (
select mt.*,
sum(nummales) over (partition by grade) - 1 as endrange_male,
sum(nummales) over (partition by grade) - nummales as startrange_male,
sum(numfemales) over (partition by grade) - 1 as endrange_female,
sum(numfemales) over (partition by grade) - numfemales as startrange_female
from magictable mt
)
select
from (select s.*,
ROW_NUMBER() over (partition by grade, gender order by student_id) as seqnum
from student s
) s join
classinfo ci
on (s.gender = 'M' and s.seqnum between startrange_male and endrange_male) or
(s.gender = 'F' and s.seqnum between startrange_female and endrange_female)
因此,这将作业信息转化为计算每个班级有多少男性和女性。你可能还有其他方法可以做到这一点,所以我在这里给出一个大概的答案。
可以统计每个年级的学生人数,男生人数,女生人数。通过从总容量中减去实际学生人数来计算“超额”学生人数。这给出了每个类的实际大小。然后按男女比例划分。
以下查询显示了如何执行此操作:
select c.*,
(c.class_limit - ((csum.maxcapacity - ssum.numstudents)/csum.numcourses)) as actsize,
(c.class_limit - ((csum.maxcapacity - ssum.numstudents)/csum.numcourses)) * (NumMales / NumStudents) as actMales,
(c.class_limit - ((csum.maxcapacity - ssum.numstudents)/csum.numcourses)) * (NumFemales / NumStudents) as actFemales
from course c join
teacher t
on c.teacher_id = t.teacher_id
(select grade, count(*) as numcourses, SUM(class_limit) as maxcapacity
from course c join
teacher t
on c.teacher_id = t.teacher_id
group by grade
) csum
on t.grade = csum.grade join
(select grade, sum(case when gender = 'M' then 1 else 0 end) as NumMales,
sum(case when gender = 'F' then 1 else 0 end) as NumFemales,
count(*) as NumStudents
from s
group by grade
) ssum
on t.grade = ssum.grade;
问题是,这是一个近似值,因为它涉及分数学生。而且,唉,真正的学生只有非分数大小。
有一个真正的解决方案来计算离散大小。不过,我只是将 NumMales 和 NumFemales 舍入到下一个整数,然后将其用于估计。这对于您的目的可能已经足够了。
并且,此解决方案中的代码用于说明解决方案。它可能有语法问题。