select Ind,ID,itemGrp.group_name as Name, ABS(SUM(CR_QTY - DR_QTY)) as Quantity, ABS(SUM(CR_AMOUNT - DR_AMOUNT)) as Value  from $trans_db.Transaction_Item_Helper det  inner join  (select ItemGrp1.group_name, Item.item_id, 'G' as Ind,ItemGrp1.group_id as ID from  $master_db.Sales_Inventory_Items item inner join  (with recursive cte (group_id, group_name, parent_id, item_id) as (  select     grp.group_id,grp.group_name,grp.parent_id, item.item_id  FROM $master_db.Sales_Inventory_Items item left outer join Sales_Inventory_Groups  grp  on item.group_id = grp.group_id  union all   select     p.group_id, p.group_name,p.parent_id, item_id  from       $master_db.Sales_Inventory_Groups  p  inner join cte   on p.group_id = cte.parent_id ) select cte.group_name, cte.item_id, cte.group_id  from cte where cte.parent_id = '$f2' ) itemGrp1  on itemGrp1.item_id = item.item_id  union  select Item2.Item_name, Item2.Item_id, 'I' as ind,Item2.Item_id as ID  from  $master_db.Sales_Inventory_Items Item2  where Item2.group_id = '$f2' ) itemGrp  on det.ItemID = itemGrp.item_id  where  ( str_to_Date(addTime(det.VoucherDate, det.Time) ,'%Y-%m-%d %H:%i:%s')>=str_to_date('$fromDateTime','%Y-%m-%d %H:%i:%s') and str_to_Date(addTime(det.VoucherDate, det.Time) ,'%Y-%m-%d %H:%i:%s')<= str_to_date('$toDateTime','%Y-%m-%d %H:%i:%s')) AND det.voucherType like '$f1' group by itemGrp.group_name ORDER BY 1,3