select 'I' as Ind, A.item_id as Id,  Item_Name as Item,   cast(sum(Opening) as decimal(10,3)) as Opening,    cast(sum(Inward) as decimal(10,3)) as Inward,    cast(sum(Issue) as decimal(10,3)) as Issued ,    cast(sum(Opening)+sum(Inward)-sum(Issue) as decimal(10,3)) AS 'Closing Stock',   round(coalesce(purch.price , coalesce(std_cost,0)) *(sum(Opening)+sum(Inward)-sum(Issue)),2)   as 'Stock Value' from    (    select trans.VoucherDate vDate, ItemID as item_id,  (case when VoucherDate < str_to_date('$fromDateTime','%Y-%m-%d %H:%i:%s') or VoucherDate is null then (dr_qty) - (cr_qty)  else 0 end) as Opening,  (case when VoucherDate >= str_to_date('$fromDateTime','%Y-%m-%d %H:%i:%s') and VoucherDate <= str_to_date('$toDateTime','%Y-%m-%d %H:%i:%s') then (dr_qty)  else 0 end )as Inward ,  (case when VoucherDate >= str_to_date('$fromDateTime','%Y-%m-%d %H:%i:%s') and VoucherDate <= str_to_date('$toDateTime','%Y-%m-%d %H:%i:%s') then (cr_qty) else 0 end )as Issue,   trans.Dr_Amount , trans.Cr_Amount  from $trans_db.Transaction_Item_Helper trans where      VoucherDate <= str_to_date('$toDateTime','%Y-%m-%d %H:%i:%s') UNION ALL  select trans.VoucherDate vDate, ItemID as item_id,  (case when VoucherDate < str_to_date('$fromDateTime','%Y-%m-%d %H:%i:%s') or VoucherDate is null then (dr_qty) - (cr_qty)  else 0 end) as Opening,  (case when VoucherDate >= str_to_date('$fromDateTime','%Y-%m-%d %H:%i:%s') and VoucherDate <= str_to_date('$toDateTime','%Y-%m-%d %H:%i:%s') then (dr_qty)  else 0 end )as Inward ,  (case when VoucherDate >= str_to_date('$fromDateTime','%Y-%m-%d %H:%i:%s') and VoucherDate <= str_to_date('$toDateTime','%Y-%m-%d %H:%i:%s') then (cr_qty) else 0 end )as Issue,   trans.Dr_Amount , trans.Cr_Amount  from $trans_db.Transaction_BOM_Helper trans where      VoucherDate <= str_to_date('$toDateTime','%Y-%m-%d %H:%i:%s') ) A  inner join $master_db.Sales_Inventory_Items inv  on A.item_id = inv.item_id  left outer join (SELECT Inventory_Item_ID, Voucher_Date, Price  FROM (SELECT  *, ROW_NUMBER() OVER (PARTITION BY Inventory_Item_ID ORDER By Voucher_Date desc, _id desc) AS rn  FROM $trans_db.purchase_invoice_details where Voucher_Date <= str_to_date('$toDateTime','%Y-%m-%d %H:%i:%s') ) x  WHERE rn = 1) purch  on A.item_id = purch.inventory_item_id  where inv.isStockItem = 1  group by inv.item_id   having sum(Opening)+sum(Inward)-sum(Issue) <> 0  order by Item