 SELECT 'I' as Ind,Item_ID, item_name as 'Item',round(Quantity,3) as 'Sales Qty',round(Subtotal,2) as 'Sales Amount',round(Std_Cost,2) as 'Std Cost',round(TotalCost,2) as 'Cost Total',round(subTotal - Totalcost,2) as 'Margin Amount',round(COALESCE((COALESCE(SubTotal,0)-COALESCE(TotalCost,0))*100/coalesce(TotalCost,0),0),2) as 'Margin %' from  (  select inv.item_id, inv.item_name, det.Quantity, det.Subtotal,INV.STD_COST,INV.STD_COST * DET.QUANTITY as TotalCost FROM $master_db.Sales_Inventory_Items inv inner join (select inventory_item_id,sum(quantity) as Quantity,sum(subTotal) as SubTotal from $trans_db.Sales_Invoice_Details where voucher_Date >= str_to_date('$fromDateTime','%Y-%m-%d %H:%i:%s') and voucher_Date <= str_to_date('$toDateTime','%Y-%m-%d %H:%i:%s') group by inventory_item_id)det on inv.Item_ID = det.Inventory_Item_ID group by inv.Item_ID) A
