您需要累積總和和聚合。以下是累計數量以及總計裝運數量:
select r.*, cume.cumequantity, coalesce(s.shipped ,0)
from received r cross apply
(select sum(r2.quantity) as cumequantity
from received r2
where r2.sku = r.sku and r2.id <= r.id
) cume left join
(select s.sku, sum(quantity) as shipped
from shipped s
group by s.sku
) s
on r.sku = s.sku
這提供了您需要回答您的問題所需的基本信息。其餘的只是算術和邏輯:
with rs as (
select r.*, cume.cumequantity, coalesce(s.shipped ,0)
from received r cross apply
(select sum(r2.quantity) as cumequantity
from received r2
where r2.sku = r.sku and r2.id <= r.id
) cume left join
(select s.sku, sum(quantity) as shipped
from shipped s
group by s.sku
) s
on r.sku = s.sku
)
select rs.ID, rs.Sku, rs.Quantity,
(case when rs.cumequantity <= rs.shipped
then rs.quantity
when rs.cumquantity > rs.shipped and
rs.cumquantity - rs.quantity < rs.shipped
then rs.shipped - rs.cumquantity - rs.quantity
else 0
end) as used,
(case when rs.cumequantity <= rs.shipped
then 0
when rs.cumequantity > rs.shipped and
rs.cumequantity - rs.quantity < rs.shipped
then rs.quantity - (rs.shipped - rs.cumequantity - rs.quantity)
else rs.quantity
end) as remaining
from rs
您正在使用哪些DBMS? Postgres的?甲骨文? –
我正在使用SQL Server 2008 R2。 – Lance
@GordonLinoff,是的,你是對的。這是一個遞增的整數。讓我改變表格。 – Lance