MySql搜索排名与标准

Jot*_*a D 6 mysql sql

我有一个名为客户的表来保存客户的数据

id  | fname  | lname  
--- | ------ | ------  
 1  | John   | Smith
 2  | Mike   | Bolton
 3  | Liz    | John
 4  | Mark   | Jobs
Run Code Online (Sandbox Code Playgroud)

我还有另一个名为call的表,可以对每个客户进行每次调用.

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    | 
Run Code Online (Sandbox Code Playgroud)

广告系列一般不计入计算.

我需要根据每个客户呼叫历史记录,通过呼叫质量排名来获取客户列表.

此列表用于呼叫客户,以便:

  • 没有被称为实际的通话活动(例如2016-09)
  • 呼叫次数减少
  • 最佳回答%(已接听电话总数/总拨打电话)

它应该看起来像这样:

| 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  
Run Code Online (Sandbox Code Playgroud)

请帮我!

Sta*_*avL 1

统计指定活动中每个客户总呼叫数和已应答呼叫数的查询

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
Run Code Online (Sandbox Code Playgroud)

然后你可以使用上面的查询作为子查询来排序

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
Run Code Online (Sandbox Code Playgroud)

您可以在结果查询中包含任何所需的列