select id, part_no, sq2-oq2 rest
from (
select tr.*, row_number() over (partition by part_no order by id) rnk
from (select i.transaction_equipmentid id, part_no, i.quantity iq,
sum(i.quantity) over (partition by part_no
order by i.transaction_equipmentid) sq1,
sum(i.quantity) over (partition by part_no) sq2,
o.quantity oq1,
max(o.quantity) over (partition by part_no) oq2
from wa_ii_tbl_tr_equipment i
left join wa_ii_tbl_tr_out_equipment o
on o.transaction_equipmentid_fk = i.transaction_equipmentid
where i.supplierid_fk = 62551 ) tr
where sq1 >= oq2 or oq2 is null )
where rnk = 1
Uní la entrada y la salida, luego uso las funciones analíticas sum()
y max()
Preparo toda la información necesaria, lo más importante es la suma acumulada. Puede verlo ejecutando la consulta más interna por separado, este alias como tr
.
El siguiente paso es solo agregar row_number()
para encontrar la(s) primera(s) fila(s) donde la entrada es mayor que la salida y mostrar esta fila y la diferencia restante.
Esta condición:or oq2 is null
es necesario mostrar también otras partes (aquí PA000535
).
Lea acerca de las funciones analíticas, hay muchos tutoriales en la red.
Datos de prueba:
create table WA_II_TBL_TR_EQUIPMENT(
TRANSACTION_EQUIPMENTID varchar2(15), DESCRIPTION varchar2(10),
SUPPLIERID_FK number(6), PART_NO varchar2(10), QUANTITY number(6));
insert into WA_II_TBL_TR_EQUIPMENT values ('TE201708000002', 'fg', 62551, 'GSDFGSG', 2);
insert into WA_II_TBL_TR_EQUIPMENT values ('TE201709000003', 'fg', 62551, 'PA000535', 7);
insert into WA_II_TBL_TR_EQUIPMENT values ('TE201709000002', 'fg', 62551, 'GSDFGSG', 9);
insert into WA_II_TBL_TR_EQUIPMENT values ('TE201708000004', 'fg', 62551, 'GSDFGSG', 10);
insert into WA_II_TBL_TR_EQUIPMENT values ('TE201708000003', 'fg', 62551, 'GSDFGSG', 2);
insert into WA_II_TBL_TR_EQUIPMENT values ('TE201709000001', 'Test', 48544, 'Test', 8);
create table WA_II_TBL_TR_OUT_EQUIPMENT(
TRANSACTION_OUT_EQUIPMENTID varchar2(15),
TRANSACTION_EQUIPMENTID_FK varchar2(15),
QUANTITY number(6));
insert into WA_II_TBL_TR_OUT_EQUIPMENT values('TOE201709000001', 'TE201708000002', 3);
Salida:
ID PART_NO REST
--------------- ---------- ----------
TE201708000003 GSDFGSG 20
TE201709000003 PA000535