简体   繁体   中英

MySQL grouping by client rather than by phone number

I have 5 tables:

  1. service_agents table
  2. clients table
  3. clients_data table (keeps track of all client data. each piece of data is entered as another row in the table. So if the client, for example, has 2 phone numbers, there will be 2 rows - with connecting (foreign key) client_id).
  4. phone_call table (keeps track of phone call, inc. phone number)
  5. phone_call_leg table (keeps track of all legs of the phone call, inc. agent_id)

I want to display anytime an agent calls a client more than 2 times in a day. This is what I've managed so far:

SELECT 
  pcl.agent_id, 
  CONCAT( sa.first_name, ' ', sa.last_name ) AS 'Agent Name', 
  pc.remote_number, 
  COUNT( pcl.agent_id ) AS 'times_called'  
FROM 
  phone_call_leg pcl 
  JOIN phone_call pc ON pcl.call_id = pc.id 
  JOIN service_agents sa ON sa.id = pcl.agent_id 
GROUP BY 
  pcl.agent_id, 
  pc.remote_number 
HAVING 
  times_called > 2 

This query returns if an agent called a specific number more than twice. But it does not take into account if 2 numbers belong to the same client. The problem will be that it doesn't catch the following scenario: the agent calls one of those numbers once and the other number twice, essentially calling the client a total of 3 times.

Question: how do I change it to check if the client has more than one phone number in the clients_data table and then see if the agent called any of those numbers (ie calling the client ) more than twice?

I'm not familiar with "phone leg" concept, but can´t you do the group_by by client_id and not number?

SELECT 
  COUNT(* ) AS 'times_called' ,
  pcl.agent_id, 
  CONCAT( sa.first_name, ' ', sa.last_name ) AS 'Agent Name', 
  pc.remote_number
FROM 
  phone_call_leg pcl 
  JOIN phone_call pc ON pcl.call_id = pc.id 
  JOIN service_agents sa ON sa.id = pcl.agent_id
  JOIN clients_data clid on clid.tel=  pc.remote_number
  JOIN clients cli on cli.id = clid.client_id 
GROUP BY 
  pcl.agent_id, 
  cli.id 
HAVING 
  times_called > 2;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM