У меня есть база данных с кучей собак, разделенных на разные цвета: красный, зеленый и желтый.
Name Color --------------- Dog1 Green Dog2 Green Dog3 Yellow Dog4 Yellow Dog5 Red Dog6 Red etc.
Позвольте сказать, что у меня есть стол со 100 собаками, тогда я хочу, чтобы их разделили на разные куски с 4 собаками в каждую жару. Проблема в том, что красная и зеленая собака не должны существовать в одинаковой жаре.
Я пробовал как с базами данных MongoDB, так и с SQL, но я не смог выяснить, возможно ли это.
В SQL я пробовал:
SELECT * FROM Dogs WHERE color IN ('green', 'yellow') OR color IN ('red', 'yellow') ORDER BY RAND() LIMIT 4;
Но тогда красные и зеленые еще могут быть выбраны вместе. Кто-нибудь получил несколько советов, как сделать это возможным?
Предположим, что ваша оригинальная таблица называется #temp:
declare @holding table (name varchar(max), color varchar(max), heat int)
declare @name varchar(max)
declare @color varchar(max)
declare @heat1 int
declare @heat2 int
declare @heat3 int
declare @heat4 int
declare @iterator int =1
while @iterator<=(Select max(cast(replace(name,'dog','') as int)) from #temp)
begin
select @color= color, @name=name from #temp where name='dog'+cast(@iterator as varchar(max))
select @heat1=count(*) from @holding where heat=1
select @heat2=count(*) from @holding where heat=2
select @heat3=count(*) from @holding where heat=3
select @heat4=count(*) from @holding where heat=4
if @color = 'red'
begin
if @heat1>=@heat2
insert @holding
select @name, @color, 2
else
insert @holding
select @name, @color, 1
end
if @color = 'yellow'
begin
if @heat1<=@heat2 and @heat1<=@heat3 and @heat1<=@heat4
insert @holding
select @name, @color, 1
else if @heat2<=@heat1 and @heat2<=@heat3 and @heat2<=@heat4
insert @holding
select @name, @color, 2
else if @heat3<=@heat1 and @heat3<=@heat2 and @heat3<=@heat4
insert @holding
select @name, @color, 3
else
insert @holding
select @name, @color, 4
end
if @color = 'green'
begin
if @heat3>=@heat4
insert @holding
select @name, @color, 4
else
insert @holding
select @name, @color, 3
end
set @iterator=@iterator+1
end
select * from @holding
order by heat, color
Это звучит глупо, но не могли бы вы просто заказать по цвету? Ваши теплоты будут скучными, как все зеленые, все желтые и т.д., Но это решит вашу проблему.
Возможно, что-то вроде
SELECT * FROM (
SELECT *, CASE WHEN Color = 'Green' THEN 1 ELSE CASE WHEN Color = 'Yellow' THEN 2 ELSE 3 END END AS o FROM dogs
) x ORDER BY x.o