Search code examples
sqlsql-servert-sql

Find the number of return calls that were done by customer care within 30 minutes of the missed call


Consider a customer care center which receives calls from customers, Starttime and Endtime denotes the conversation start time and end time. Missed calls are the calls where no conversation happened. For any missed call, the customer care returns the call.

For below given table,

CREATE TABLE CustomerCare (fromnumber INT, tonumber INT, starttime DATETIME,endtime DATETIME)

INSERT INTO CustomerCare (fromnumber,tonumber,starttime,endtime) 
VALUES
(100,1800,'2019-08-13 18:40:00','2019-08-13 18:40:00'),
(1800,100,'2019-08-13 18:55:00','2019-08-13 18:57:00'),
(200,1800,'2019-08-13 19:30:00','2019-08-13 19:30:00'),
(1800,200,'2019-08-13 20:05:00','2019-08-13 20:10:00'),
(300,1800,'2019-08-13 21:00:00','2019-08-13 21:00:00'),
(1800,300,'2019-08-13 21:20:00','2019-08-13 21:25:00'),
(400,1800,'2019-08-13 07:00:00','2019-08-13 07:00:00'),
(500,1800,'2019-08-13 8:00:00','2019-08-13 8:05:00')

enter image description here

Find the number of return calls that were done by customer care within 30 minutes of the missed call.

Fourth row indicates one such return call.

Can anyone help a SQL query.


Solution

  • first you find the missed call, then you find the call back by customercare. And you find the time different

    select  *
    from    CustomerCare mc
            cross apply -- get call back time
            (   
                select  top 1 *
                from    CustomerCare x
                where   x.fromnumber    = mc.tonumber
                and     x.tonumber  = mc.fromnumber
                and     x.starttime > mc.starttime
                order by x.starttime
            ) cb
    where   mc.starttime = mc.endtime  -- missed call
    and     datediff(minute, mc.starttime, cb.starttime) > 30 -- time different between 
                                                              -- missed call and callback