set nocount on
--студенты
declare @student table
(
StudentId int not null primary key,
CourseId int not null,
Gender char(1) not null
)
--секции курсов
declare @sections table
(
SectionId int not null,
CourseId int not null
)
--студенты курса 1
--мальчики
insert into @student(StudentId, CourseId, Gender) values(1,1,'M')
insert into @student(StudentId, CourseId, Gender) values(2,1,'M')
insert into @student(StudentId, CourseId, Gender) values(3,1,'M')
insert into @student(StudentId, CourseId, Gender) values(4,1,'M')
insert into @student(StudentId, CourseId, Gender) values(5,1,'M')
insert into @student(StudentId, CourseId, Gender) values(6,1,'M')
--девочки
insert into @student(StudentId, CourseId, Gender) values(7,1,'F')
insert into @student(StudentId, CourseId, Gender) values(8,1,'F')
insert into @student(StudentId, CourseId, Gender) values(9,1,'F')
--студенты курса 2
--мальчики
insert into @student(StudentId, CourseId, Gender) values(10,2,'M')
--девочки
insert into @student(StudentId, CourseId, Gender) values(11,2,'F')
--секции
insert into @sections(SectionId, CourseId) values(1,1)
insert into @sections(SectionId, CourseId) values(2,1)
insert into @sections(SectionId, CourseId) values(3,2)
select st.StudentId, st.CourseId, st.Gender, sec.SectionId
from
(
select StudentId, CourseId, Gender,
--номер студента в пределах курса и пола
studentIdx = row_number() over(partition by CourseId, Gender order by StudentId) -1
from @student
) st
inner join
(
select SectionId, CourseId,
--номер секции в пределах курса
sectionIdx = row_number() over(partition by CourseId order by SectionId) - 1,
--количество секий в курсе
SectionCount = count(*) over(partition by CourseId)
from @sections
) sec on
--связать секцию курса и студента
sec.CourseId = st.CourseId
--равномерно распределить в каждую секцию
and sec.sectionIdx = (st.studentIdx % sec.SectionCount)
order by CourseId, SectionId, Gender, StudentId