--物品装箱问题
/*
有一个表,字段为:物品名,件数。
记录: 物A 54
物B 35
物C 23
物D 98
物E 43
现要对这些物品统一装箱,统一装60个一箱,那么第一箱物A装54个,物B装6个,第二箱物B装29个,物C装23个,物D装8个,依此类推。
请问怎么解决?
*/
if object_id('[tb]') is not null drop table [tb]
go
create table [tb](物品名 varchar(10),件数 int)
insert [tb]
select '物A', 54 union all
select '物B', 35 union all
select '物c', 23 union all
select '物d', 98 union all
select '物e', 43
go
set nocount on
declare @物品 varchar(10),@数量 int,@箱号 int,@剩余 int
declare @t table(箱号 int,物品 varchar(10),数量 int)
declare cur cursor for select * from tb
open cur
fetch cur into @物品,@数量
set @箱号=1
while @@fetch_status=0
begin
while 1=1
begin
select @剩余=isnull(sum(数量),0) from @t where 箱号=@箱号
if @数量>60 - @剩余
begin
set @数量=@数量-(60 - @剩余)
insert @t select @箱号, @物品,60 - @剩余
set @箱号=@箱号+1
end
else
begin
insert @t select @箱号,@物品,@数量
break
end
end
fetch cur into @物品,@数量
end
close cur
deallocate cur
select * from @t
/*
箱号 物品 数量
----------- ---------- -----------
1 物A 54
1 物B 6
2 物B 29
2 物c 23
2 物d 8
3 物d 60
4 物d 30
4 物e 30
5 物e 13
*/