Помогите, пожалуиста, сбалансированно распределить.

Ann2
Дата: 06.06.2011 21:25:02
У меня такая задача:
Имеется таблица А:
студент курс пол

и другая таблица Б:
студент курс секция

в этоi таблице на каждыи курс - (2 или 3 секции на курс)

мне нужно из первои таблицы сбалансированно распределить девочек и мальчиков во вторую (insert).
Т.е если у меня 90 человек идет на курс, то в первую секцию идут 15 девочек и 15 мальчиков, во вторую 15/15 и в третью 15/15.
Число девочек и мальчиков может быть разным, не 45/45 а например 30/60 и у меня несколько курсов с разным количеством студентов и разным количеством секции.
Помогите, пожалуиста, написать эти лупы.

Спасибо.
Alexes
Дата: 07.06.2011 09:57:00
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
	

Ann2
Дата: 08.06.2011 23:51:37
Alexes,

Спасибо огромное! То, что надо.

Аnn