我有一个数据库,里面有一堆分为不同颜色的狗:红色,绿色和黄色。
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;
但是红色和绿色仍然可以一起选择。任何人都有一些提示如何使这成为可能吗?
答案 0 :(得分:0)
假设您的原始表名为#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
答案 1 :(得分:0)
这听起来很傻,但你不能按颜色订购吗?你的热量会像所有绿色,全黄色等一样无聊,但它会解决你的问题。
也许像
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