日期:2014-05-17 浏览次数:20966 次
--库存表 t_storeitem id materialid totalAmount 1 1001 10000 2 1002 20000 3 1003 30000 --订单表 t_orderticket id materialid needAmount 1 1001 100 2 1001 250 3 1001 150 4 1002 200 5 1002 150 6 1003 300 --期望查询结果 orderticketid materialid remainAmount 1 1001 10000 2 1001 9900 3 1001 9650 4 1002 20000 5 1002 19800 6 1003 30000
create table t_storeitem as select 1 id,1001 materialid,10000 totalAmount from dual union select 2,1002,20000 from dual union select 3,1003,30000 from dual; create table t_orderticket as select 1 id,1001 materialid,100 needAmount from dual union select 2,1001,250 from dual union select 3,1001,150 from dual union select 3,1002,200 from dual union select 3,1002,150 from dual union select 3,1003,300 from dual; select rownum as orderticketid,a.materialid,lag(a.totalAmount-b.needAmount,1,a.totalAmount) over(partition by a.materialid order by a.id) as remainAmount from t_storeitem a,t_orderticket b where a.materialid=b.materialid
------解决方案--------------------
貌似这样可以?
select t1.id,t1.materialid,t1.needAmount, nvl(totalamount-(select sum(needAmount) from t_orderticket a where a.materialid=t1.materialid and a.id<t1.id),totalamount) c from t_orderticket t1,t_storeitem t2 where t1.materialid=t2.materialid order by t1.materialid,t1.id
------解决方案--------------------
楼上的那个,就很直观。
也可以改成这样(用开窗函数):
select o.id,
o.materialid,
o.needAmount,
i.totalamount-sum(o.needAmount) over(partition by o.materialid order by o.id)+o.needamount
from t_storeitem i, t_orderticket o
where i.materialid = o.materialid
order by o.materialid