這裏,你可以採取的辦法。
關鍵的想法是統計每個班級的男女學生人數,然後分配他們。如果我們掌握了這些信息,這項任務非常簡單。因此,假設我們有它:
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四捨五入到下一個整數,並將其用於估算。這對你的目的可能已經足夠了。
而且,此解決方案中的代碼是爲了說明解決方案。它可能有句法問題。
'我需要他們是性別平衡的.. ..但沒有你的設置中的性別信息..? –
性別平衡是性別歧視!如果只有我和其他人註冊,並與其餘的女性說服,我們被迫純粹基於我們的生殖器進入不同的課程!我反對:P – Wrikken
對不起,忘了添加有一個字段是爲M或F的學生 – Mysteri0n