[sql server] 物品装箱问题

--物品装箱问题
/*

http://topic.csdn.net/u/20100703/16/bcc2efaf-5aee-424d-b022-473282a168ae.html?seed=657778656&r=66694963#r_66694963

有一个表,字段为:物品名,件数。
记录: 物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
*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值