日期:2014-05-18  浏览次数:20455 次

请教整单分拆的问题,请大家帮帮忙,看有什么好的方法,谢谢!
有一条库存表TBA,被借出了以下货物:
名称 数量 时间
a -2 20071011
a -1 20071012
a -3 20071013

现在,还来了两条数据
a 5


这时,我们应该拆分成
a 2  
a 1
a 2
来按时间顺序充平库存,不知道我说的有没有明白,请各位帮忙,谢谢。
(是否一定要用临时表来解决呢?)


------解决方案--------------------
SQL code
--生成测试数据
create table TBA(名称 varchar(10),数量 int,时间 varchar(10))
insert into TBA values('a',-2,20071011) 
insert into TBA values('a',-1,20071012) 
insert into TBA values('a',-3,20071013) 

create table TBB(名称 varchar(10),数量 int)
insert into TBB values('a',5) 

--执行查询处理
select
    a.名称,
    case 
       when a.初期-a.数量<b.数量 then -a.数量
       else b.数量-a.初期
    end as 数量
from
    (select t.*,(select isnull(sum(-数量),0) from TBA where 名称=t.名称 and 时间<t.时间) as 初期 from TBA t) a,
    TBB b
where
    a.名称=b.名称 
    and 
    a.初期<b.数量

--输出查询结果
/*
名称         数量          
---------- ----------- 
a          2
a          1
a          2
*/

--删除测试数据
drop table TBA,TBB

------解决方案--------------------
keqi
------解决方案--------------------
mark
------解决方案--------------------
好强呀.
------解决方案--------------------
强啊呀