SELECT 
DID,
sum(Inbound) as InboundCalls,
sum(Outbound) as OutboundCalls,
Durations/(Calls- MissedCalls) as Average 

FROM (
          SELECT wcdr.cdr_id as CdrId,
          wcdr.Node as Node,
          wcdr.missed_id as MId,
          wcdr.Zone,
          wcdr.Person,
          wcdr.Source,
          wcdr.Destination,
          wcdr.StartTime,
          cin.Name,
          wcdr.Duration,
          vm.id as vmid,
          sum( if ( Inbound & 1 = 1, 1, 0) ) as Inbound,
          sum( if( Inbound & 1 = 1 , 0, 1 ) ) as Outbound,
          sum( if ( Inbound & 1 = 1, 1, 0) ) + sum( if( Inbound & 1 = 1, 0, 1 ) ) as Calls,
          sum( if ( Inbound & 1 = 4, 1, 0) ) as MissedCalls,
          sum( wcdr.Duration ) as Durations,
          di.DID as DID,
          di.Account as Account
          FROM WebCDR wcdr
          JOIN VoIPNumber vm ON vm.id = wcdr.Node
          LEFT JOIN CallerId_Name cin ON cin.id = vm.id
          JOIN DIDInventory di ON di.id = vm.DID
          WHERE  wcdr.Zone = 479939  
          GROUP BY Node
          ) cdr   
GROUP BY Node  

