Average mysql with multiple conditions

Asked

Viewed 22 times

0

I am mounting a graph containing the amount of CHATS that were answered in a given time, example:

1-30s -> 20 chats answered

31-60s -> 66 chats answered

60-120s -> 4 chats answered

I’m confused on how to return this using a query

The basic structure of my table is:

ID | Title | Chat duration

1 | Test | 20

2 | Teste2 | 66

To get the average duration, I use the code below:

$filter['filtergt']['user_id'] = 0;           
$filterCombined = array_merge_recursive($filter,array('filtergt' => array('chat_duration' => 0),'filter' =>  array('status' => erLhcoreClassModelChat::STATUS_CLOSED_CHAT)));            
   return erLhcoreClassChat::getCount($filterCombined, 'lh_chat', 'AVG(chat_duration)');

I believe with Queries it solves, but I’m not sure

Obs: only the query solves, or the idea, and I implement in the system

Take all the chats and do the one-to-one check of the duration I believe is not feasible, thinking of large amounts of existing chats

1 answer

1


Yes, you can do this only with SQL. You can use the structure marry to define a common value between the records of each interval and, later, to group them together, calculating the amount of records in each group.

For example:

select
  case
    when duration between 0 and 30 then '0-30s'
    when duration between 31 and 60 then '30-60s'
    else '60-120s'
  end as tempo,
  count(*) as total
from atendimento
group by tempo

See working on Sqlfiddle

  • Hello, it works correctly, however I added 2 more conditions (60-90 and 90-120) and for some reason, the fifth (that would be the "Else") is not activated, nor if I put other conditions, only returns the first 4, but works correctly with this exception

  • Make an example by playing what you did and post the link.

  • here is http://sqlfiddle.com/#! 9/56ac7/1/0

  • I didn’t understand what was wrong there. The result seemed right.

  • Friend, I was going to answer now. My fault, I didn’t notice the order in which the records returned, and I thought one was missing, it’s really correct, sorry!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.