如何计算平均间隔时间

时间:2018-08-07 08:35:24

标签: mysql sql

如何计算平均间隔时间

+-------------+----------+----------+--------+------------------+
| customer_id |   date   |   time   | answer | missed_call_type |
+-------------+----------+----------+--------+------------------+
|         101 | 2018/8/3 | 12:13:00 | no     | employee         |
|         102 | 2018/8/3 | 12:15:00 | no     | customer         |
|         103 | 2018/8/3 | 12:20:00 | no     | employee         |
|         102 | 2018/8/3 | 15:15:00 | no     | customer         |
|         101 | 2018/8/3 | 18:15:00 | no     | employee         |
|         105 | 2018/8/3 | 18:18:00 | no     | customer         |
|         102 | 2018/8/3 | 19:18:00 | no     | employee         |
+-------------+----------+----------+--------+------------------+

我有一张看起来像这样的表,想为那些未接电话的人计算平均间隔时间。对于此示例,平均间隔时间为:

  

{(18:15:00-12:13:00)+ [(19:18:00-15:15:00)+(15:15:00-12:15:00)] / 2} / 2

1 个答案:

答案 0 :(得分:2)

请找到以下用于MSSQL的代码,

CREATE TABLE customer_data (customer_id BIGINT, date DATE, time time, answer VARCHAR(100), missed_call_type VARCHAR(100));

INSERT INTO customer_data
VALUES
(101, '2018/8/3', '12:13:00', 'no', 'employee'),
(102, '2018/8/3', '12:15:00', 'no', 'customer'),
(103, '2018/8/3', '12:20:00', 'no', 'employee'),
(102, '2018/8/3', '15:15:00', 'no', 'customer'),
(101, '2018/8/3', '18:15:00', 'no', 'employee'),
(105, '2018/8/3', '18:18:00', 'no', 'customer'),
(102, '2018/8/3', '19:18:00', 'no', 'employee')

select cd.customer_id, answer, missed_call_type,
        CAST(CAST(cd.date as VARCHAR(10))+' ' +CAST(cd.time as VARCHAR(10)) as datetime) as date,
        ROW_NUMBER() OVER(PARTITION BY cd.customer_id ORDER BY date desc, time desc) as ranks
INTO #temP
from customer_data cd
order by cd.customer_Id, ranks;

select AVG(DATEDIFF(MINUTE, x1.date, x2.date)) as avg_mins
from #temP x1
INNER JOIN #temP x2 ON x1.customer_id = x2.customer_id 
WHERE x2.ranks = (x1.ranks-1)