在mysql中根据周数进行平均

时间:2018-08-09 12:20:25

标签: mysql

我正在尝试完成一个查询,该查询需要平均两个指标(入站呼叫和未接呼叫)。但是我从来没有在一周中的每一天和每个小时的时间间隔进行细粒度的工作,所以我不确定我的计算是否正确,更不用说获得正确的平均值了。

基本上,从1/1/18开始,我希望在周一至周五的上午7点至下午6点之间每小时平均入站电话和未接电话。我们被关闭了7天,我得到了48行,所以这就是我的期望。

所以如果最近3个星期一看起来像:

creationtimestamp   | Legtype1  |  answered  

07/23/18 08:15:00   |     2     |     0             
07/23/18 08:25:00   |     2     |     1           
07/23/18 08:35:00   |     2     |     1               
07/30/18 08:15:00   |     2     |     0           
07/30/18 08:25:00   |     2     |     0           
07/30/18 08:35:00   |     2     |     0           
07/30/18 08:45:00   |     2     |     1           
07/30/18 08:55:00   |     2     |     0           
08/06/18 08:15:00   |     2     |     0           
08/06/18 08:25:00   |     2     |     1           
08/06/18 08:35:00   |     2     |     0           
08/06/18 08:45:00   |     2     |     0  

在星期一上午8点至9点之间,总共有12个呼叫,有4个未接。如果我要查询从8到9的三个星期一,我会期望:

Monday | 8 | 4 | 1.3

但是我不知道如何计算每个工作日的所有通话总和,将这些总和除以该工作日的数量?我在下面的查询中当前使用的是“ SUM”而不是平均值,但是我不确定该如何取平均值,因为它取决于每个工作日的数量。

SELECT 
    dayname(s.creationtimestamp) as day, -- weekdays
    HOUR(s.creationtimestamp) as Hour, -- Hours
    sum(case when legtype1 = 2 then 1 else 0 end) as total_calls, -- total inbound
    sum(case when  legtype1 = 2 and answered = 0 then 1 else 0 end)as total_missed

FROM session s
WHERE (s.creationtimestamp >= '2018-01-01' AND creationtimestamp < now())
and WEEKDAY(s.creationtimestamp) BETWEEN 0 AND 4 -- Monday through friday
AND HOUR(s.creationtimestamp) between  7 and 18 -- 7am to 6pm
GROUP BY dayname(s.creationtimestamp),  HOUR(s.creationtimestamp)
order by dayofweek(s.creationtimestamp), hour asc;

要重申:该查询有效,但是我不确定是否可以根据从一年的第一天到现在的每个工作日和小时段正确汇总。

这是一个小提琴: http://sqlfiddle.com/#!9/7b6b72

1 个答案:

答案 0 :(得分:1)

我认为一切对您平均都好一点,希望下面的查询对您有所帮助

select day,Hour,Avg(total_calls) as avg_total_calls,
Avg(total_missed) as avg_total_missed from
(
SELECT 
    dayname(s.creationtimestamp) as day, -- weekdays
    HOUR(s.creationtimestamp) as Hour, -- Hours
    sum(case when legtype1 = 2 then 1 else 0 end) as total_calls, -- total inbound
    sum(case when  legtype1 = 2 and answered = 0 then 1 else 0 end)as total_missed

FROM session s
WHERE (s.creationtimestamp >= '2018-01-01' AND creationtimestamp < now())
and WEEKDAY(s.creationtimestamp) BETWEEN 0 AND 4 -- Monday through friday
AND HOUR(s.creationtimestamp) between  7 and 18 -- 7am to 6pm
GROUP BY dayname(s.creationtimestamp),  HOUR(s.creationtimestamp)

) as T group by day,Hour 
order by day,Hour asc