私はインベントリテーブルを作成し、サンプルデータを入力しました。 これは、そのためのSQLコードです。あなたが将来的に助けを求めているとき、そのようなメタデータを共有してみてください:)
create column table InventoryItems
(
Department varchar(10),
Product varchar(10),
Date date,
Quantity int,
Indicator varchar(10)
);
insert into InventoryItems select 'D001','P001','20170701',1000,'ADD' from dummy;
insert into InventoryItems select 'D001','P001','20170710',2000,'ADD' from dummy;
insert into InventoryItems select 'D001','P001','20170715',3000,'ADD' from dummy;
insert into InventoryItems select 'D001','P001','20170716',2000,'ADD' from dummy;
insert into InventoryItems select 'D001','P001','20170718',5500,'SUBTRACT' from dummy;
insert into InventoryItems select 'D001','P002','20170712',3000,'ADD' from dummy;
insert into InventoryItems select 'D001','P002','20170714',2000,'ADD' from dummy;
insert into InventoryItems select 'D001','P002','20170715',4000,'SUBTRACT' from dummy;
サンプル・テーブルおよびデータの準備ができたら、私は高齢化のためのSQLScriptコードに従って調製しました。それは多分難しい理解し、コードを追跡するので、私はあなたの問題を共有し、stock aging SQL calculation on SAP HANA database
で詳細なソリューションを提供し、ここであなたが
with Ins as (
select
row_number() over (partition by Product order by date) as AddId,
*,
sum(Quantity) over (partition by Product order by Date rows unbounded preceding) as sumIn,
sum(Quantity) over (partition by Product order by Date desc rows unbounded preceding) as sumX
from InventoryItems
where
Indicator = 'ADD'
), Outs as (
select
row_number() over (partition by Product order by date) as AddId,
*,
sum(Quantity) over (partition by Product order by Date rows unbounded preceding) as sumOut
from InventoryItems
where
Indicator = 'SUBTRACT'
), Inv as (
select
ins.Product, max(sumIn) - max(ifnull(sumOut,0)) as inv
from Ins
left join Outs
on ins.Product = outs.Product
group by ins.Product
), calc as (
select
Ins.*,
Inv.inv,
inv-sumx as diff
from Ins
left join Inv
on ins.Product = inv.Product
)
select
Department, Product, Date,
case when diff > 0 then quantity else quantity-abs(diff) end as Quantity,
DAYS_BETWEEN(Date,current_date) as AgeingInDays
from (
select *, 1 as rn from calc where diff >= 0
union all
(
select * from (
select
*, row_number() over (partition by Product order by diff desc) as rn
from calc
where diff < 0
) t where rn = 1
)
)
order by Product, AddId
をあなたの要件を満たす支援するためにSQLコードであり、これは出力され上記のSQLブロックの実行、私はそれが役に立てば幸い
、
誰の?助けてください –