标准为

时间:2016-09-06 05:26:19

标签: mysql sql

我有一个名为客户的表格,用于保存客户的数据

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

我还有一个名为来电的表,可以保持每个客户的每次通话。

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    | 

广告系列常规不计入计算。

我需要根据每个客户通话记录获得通话质量排名的客户列表。

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

  • 没有调用实际的通话广告系列(例如 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  

请帮助我!

1 个答案:

答案 0 :(得分: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

然后,您可以使用上面的查询作为子查询来订购

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

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