您好,使用以下过程,您可以实现所述的报告格式。但是,为了处理FIFO的细节,您应该避免在MySQL中创建这些逻辑。
SELECT @bal_qty:=0,@old_qty:=0,@old_qty_price:=0,@new_qty:=0,@new_qty_price:=0;
CREATE TEMPORARY TABLE test1
SELECT id, tanggal as date,
@remarks:=if(id_jenis_transaksi=1,'Buy','Use') as remarks,
@buy_qty:=if(id_jenis_transaksi=1,jumlah,0) as buy_qty,
@buy_price:=if(id_jenis_transaksi=1,harga,0) as buy_price,
@buy_total:=(@buy_qty * @buy_price) as buy_total,
@use_qty:=if(id_jenis_transaksi=2,jumlah,0) as use_qty,
@use_qty_detail:=if(@remarks='Use',if(@old_qty>0,@old_qty, @use_qty),0) as use_qty_detail,
@use_price:=@old_qty_price as use_price,
@use_total:=(@use_qty * @use_price) as use_total,
@bal_qty:=if(@remarks='Buy',@bal_qty + @buy_qty, if(@bal_qty>@use_qty,@bal_qty - @use_qty, @bal_qty)) as bal_qty,
@old_qty:=if(@old_qty > 0, @old_qty, if(@remarks='Use',@bal_qty, @old_qty)) as old_qty,
@old_qty_price:=if(@old_qty_price > 0, @old_qty_price, @buy_price) as old_qty_price,
@new_qty:=if(@old_qty>0,@buy_qty, if(@new_qty>0, @new_qty,0)) as new_qty,
@new_qty_price:=if(@old_qty_price > 0 and @buy_price > 0, @buy_price, if(@new_qty_price>0,@new_qty_price,0)) as new_qty_price,
@bal_qty_detail:=if(@old_qty > 0, @old_qty, @buy_qty) as bal_qty_detail,
@bal_price:=@old_qty_price as bal_price,
@bal_total:=(@bal_qty_detail* @old_qty_price) as bal_total,
@split_flag:=if(@bal_qty != @buy_qty and @bal_qty != @old_qty,1,0) as split_flag
FROM persediaan_source;
CREATE TEMPORARY TABLE test2 select * from test1 where split_flag=1
SELECT @cnt:=0;
SELECT (@cnt:=@cnt + 1) as id, date, remarks, buy_qty, buy_price, buy_total, use_qty, use_qty_detail, use_price, use_total, bal_qty, bal_qty_detail, bal_price, bal_total
FROM (
(SELECT * FROM test1)
UNION ALL
(SELECT id, date, remarks, 0 as buy_qty, 0 as buy_price, 0 as buy_total, 0 as use_qty,
@used_qty:=(use_qty - use_qty_detail) as use_qty_detail,
if(remarks='Use',@new_qty_price,0) as use_price,
(@used_qty * new_qty_price) as use_total, 0 as bal_qty, 0 as old_qty,
0 as old_qty_price, 0 as new_qty,0 as new_qty_price,
@bal_qty_detail:=if(remarks='Buy', buy_qty, bal_qty) as bal_qty_detail,
new_qty_price as bal_price,
(@bal_qty_detail * new_qty_price) as bal_total, split_flag
FROM test2)
) as t order by 2