Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql search ranking with criteria

Tags:

sql

mysql

I have table named customers that keeps the customer's data

id  | fname  | lname  
--- | ------ | ------  
 1  | John   | Smith
 2  | Mike   | Bolton
 3  | Liz    | John
 4  | Mark   | Jobs

And i have another table named calls that keeps each call made to each customer.

id |     timestamp     | customer_id | campaign | answered |
 1 |2016-09-05 15:24:08|      1      |  2016-09 |     1    |
 2 |2016-09-05 15:20:08|      2      |  2016-09 |     1    |
 3 |2016-08-05 15:20:08|      2      |  2016-08 |     1    |
 4 |2016-08-05 13:20:08|      3      |  2016-08 |     1    |
 5 |2016-08-01 15:20:08|      3      |  2016-08 |     0    |
 5 |2016-08-01 12:20:08|      4      |  General |     1    | 

Campaign General Doesn't count towards the calculations.

I need to get a list of customers ordered by ranking of calling quality based on each customer calling history.

This list is use to call the customers in order that:

  • Hasn't been called on the actual calling campaign (ex.2016-09)
  • Has fewer calls
  • Best % answered (total calls answered / total calls made)

It should look something like this:

| id | fname  | lname | %ans | called actual campaign | total calls | rank |
|----|--------|-------|------|------------------------|-------------|------|
| 4  | Mark   | Jobs  | N/A  |          no            |      0      |   1  |
| 3  | Liz    | John  |  50  |          no            |      2      |   2  |
| 1  | John   | Smith | 100  |          yes           |      1      |   3  | No Show  
| 2  | Mike   | Bolton| 100  |          yes           |      2      |   4  | No Show  

Please help me!

like image 377
Jota D Avatar asked Sep 06 '16 05:09

Jota D


1 Answers

The query which counts for each customer total calls and answered calls for the specified campaign

select 
    c.id,
    count(*) as total_calls,
    sum(case when answered=1 then 1 else 0 end) as answered_calls
from customer c
     join calls cs on c.id=cs.customer_id
where cs.campaign='2016-09'
group by c.id

Then you can use the query above as a subquery to order

select sub.id, (@rank:=@rank+1) as rank
from (the subquery above) sub, (select @rank:=1)
order by 
  case when sub.total_calls=0 then 0 else 1,
  sub.total_calls, 
  sub.answered_calls*100/sub.total_calls

You can include any desired columns in the result query

like image 126
StanislavL Avatar answered Nov 09 '22 20:11

StanislavL