2015-04-20 46 views
1

我有一個sql表中有以下列。第一個表格顯示收到的數量,第二個表格是已發貨的數量。第二個表給我們提供了SKU 1和數量60總數量70對SKU 2.在SQL中,如何根據每行的容量向每行分配扣除額?

Received Table 
Id Sku Quantity 
1 1 30  
2 1 20 
3 1 100 
4 2 600 

Shipped Table 
Id Sku Quantity 
1 1 50 
2 1 20 
3 2 60 

我需要一個視圖,顯示多少量相對於接收到的表被運。現在我想在此表中的每行中分配每個SKU的總數,這應該給我以下結果:

ID Sku Quantity Used Remaining 
1 1  30   30  0 
2 1  20   20  0 
3 1  100  20  80 
4 2  600  60  540 
+0

您正在使用哪些DBMS? Postgres的?甲骨文? –

+0

我正在使用SQL Server 2008 R2。 – Lance

+0

@GordonLinoff,是的,你是對的。這是一個遞增的整數。讓我改變表格。 – Lance

回答

2

您需要累積總和和聚合。以下是累計數量以及總計裝運數量:

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 
+0

這工作。謝謝。 – Lance