我有两张桌子。一个保存特定单位的数量。另一个保留了历史上这些单位的数量,日期和成本。
所以在我的第一张表中,我会说单位“ABC”的数量为50
在第二个表格中,我的数据如下:
Unit Date arrived Quantity Cost
---- ------------ -------- -----
ABC 11/1 100 $3.00
ABC 11/4 15 $5.00
ABC 11/5 25 $6.00
所以在这个例子中,我需要根据先进先出系统计算50个项目的值。对于50个项目,数学看起来像这样:
25 x $6.00
15 x $5.00
10 x $3.00
此商品的总价值为$ 255.00
所以我需要用大约300,000件物品做这件事,我需要一个“简单的按钮”。目前正在使用MS Access& SQL挖掘我的数据。因此,任何与这两个平台相关的解决方案都会很棒。
答案 0 :(得分:2)
此: -
select s.unit, dv.cost_2d+((s.quantity-dv.quantity_2d)*dv.cost) as valuation
from (
select
d.*,
isnull((
select sum(csq.quantity)
from #delivery csq
where csq.unit=d.unit
and csq.arrived>d.arrived
),0) as quantity_2d,
isnull((
select sum(csq.quantity*csq.cost)
from #delivery csq
where csq.unit=d.unit
and csq.arrived>d.arrived
),0) as cost_2d
from #delivery d
-- possible optimization - reduces the number of rows
-- if we have enough to calculate value of stock held
--join #stock s on s.unit=d.unit
--and isnull((
-- select sum(csq.quantity)
-- from #delivery csq
-- where csq.unit=d.unit
-- and csq.arrived>d.arrived
-- ),0)<=s.quantity
-- you'd need to test if it helps/hinders with your dataset/schema
) as dv
join #stock s on s.unit=dv.unit
where dv.quantity+dv.quantity_2d>=s.quantity
and dv.quantity_2d<s.quantity
生产: -
unit valuation
abc 255.00
如果来自: -
create table #stock (
unit varchar(10),
quantity int
)
create table #delivery (
unit varchar(10),
arrived date,
quantity int,
cost money
)
insert into #stock values ('abc',50)
insert into #delivery values ('abc','2013-11-01',100,3)
insert into #delivery values ('abc','2013-11-04',15,5)
insert into #delivery values ('abc','2013-11-05',25,6)
----------- UPDATE -----------------------------------
这是另一个版本,可能会或可能不会更快运行 - 取决于您的数据集/架构: -
select dv.unit, dv.cost_2d+((dv.instock-dv.quantity_2d)*dv.cost) as valuation
from (
select
d.*,
isnull((
select sum(csq.quantity)
from #delivery csq
where csq.unit=d.unit
and csq.arrived>d.arrived
),0) as quantity_2d,
isnull((
select sum(csq.quantity*csq.cost)
from #delivery csq
where csq.unit=d.unit
and csq.arrived>d.arrived
),0) as cost_2d,
s.quantity as instock
from #delivery d
join #stock s on s.unit=d.unit
and s.quantity between isnull((
select sum(csq.quantity)
from #delivery csq
where csq.unit=d.unit
and csq.arrived>d.arrived
),0) and isnull((
select sum(csq.quantity)
from #delivery csq
where csq.unit=d.unit
and csq.arrived>d.arrived
),0) + d.quantity
) as dv