开仓和平仓

时间:2018-01-10 12:18:46

标签: sql oracle

我的数据如图所示,我需要打开和关闭库存数据。

Input_data

WAREHOUSECODE   PRODUCT_CODE    STOCK_DATE  QUANTITY    STOCKVALUE_SC
    B12           2210008       31-DEC-17     2.5           10.815
    B12           2210008       31-DEC-17     5             21.63
    B12           2210008       08-JAN-18    -1             -4.326
    B12           2210008       08-JAN-18     1              4.326
    B12           2210008       08-JAN-18    -1             -4.326

预期产出

PRODUCTKEY  WAREHOUSECODE   PRODUCT_CODE    STOCK_DATE  OPENING_STOCK   TRANSACTION_Qty CLOSING_STOCK   
B12-2210008     B12             2210008     31-DEC-17         0              7.5            7.5
B12-2210008     B12             2210008     08-JAN-18         7.5            -1             6.5

感谢您的支持。

此致 Viresh

1 个答案:

答案 0 :(得分:0)

我假设您使用的是SQL Server 2008 R2或更高版本。

以下是使用窗口函数执行此操作的方法:

with raw_data as (
  select
   warehousecode + convert(varchar(10), product_code) as productKey,
   warehousecode,
   product_code,
   stock_date,
   sum(quantity) as transaction_qty
  from Stock
  group by warehousecode, product_code, stock_date
)
select 
  productKey,
  warehousecode,
  product_code,
  stock_date,
  sum(transaction_qty) over (
    partition by productKey
    order by stock_date
  ) - transaction_qty as opening_stock,
  transaction_qty,
  sum(transaction_qty) over (
    partition by productKey
    order by stock_date
  ) as closing_stock
from raw_data
;

SQLFiddle:http://sqlfiddle.com/#!6/29064/12