`
xys_777
  • 浏览: 203911 次
  • 性别: Icon_minigender_1
  • 来自: 大连
社区版块
存档分类
最新评论

[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
*/

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics