Informix SQL: Calculate the difference in seconds between timestamps in a stacked dataset. Example within.

There is a table in a Informix database that has stacked data that represents call center agents as they go about their day. LoggedIn or 1 is the first state they enter into on the phones. They can then move to other states such as ready (3) or not ready (2).

I would like to calculate the time in seconds between the logged in (1) and logout (7) states.

There is a example worksheet with the original data that I am working with as well as the desired results on another tab.

This is Informix SQL so my options are limited to functions within Informix and standard SQL.
StateDataExample.xlsx
Ryan SimmonsBusiness Analyst IIIAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

OMC2000Commented:
It should be like the following

select d1.eventdatetime, d2.eventdatetime, (d2.eventdatetime - d1.eventdatetime)::interval second(6) to fraction
from stateDataExample d1 inner join stateDataExample d2 on d1.agentid = d2.agentid
and d1.eventtype=1 and d2.eventtype=7

Open in new window


we join records for Logging In (1) and logout (7) and extract datetime value for login from datetime value for logout and cast it to interval data type where value is represented in seconds with 6 digits max and fraction (3 digits by default
0
Ryan SimmonsBusiness Analyst IIIAuthor Commented:
I see what you are trying to do (determine the time only between eventtype 1 and 7) but it doesn't work and it doesn't match up with the desired result set in the example document.

I believe what we need to do is try and join on the eventdatetime. This would be easier if the table had a corresponding end timestamp that we could join on.

This is my attempt starting with your code and isolating it to one agent for now. This currently returns a lot of dupes because it is joining every timestamp in table a with the corresponding timestamp in table b. I am going to keep working with it and see if I can get it to work using a Min or Max function on the timestamps.

SELECT a.agentid, a.eventtype, b.eventtype, a.eventdatetime, b.eventdatetime, (b.eventdatetime - a.eventdatetime)
FROM AgentStateDetail a
LEFT JOIN AgentStateDetail b on a.agentid = b.agentid
AND b.eventdatetime > a.eventdatetime
WHERE a.eventdatetime >= TO_DATE('01-02-2018 00:00:00','%m-%d-%Y %H:%M:%S')+5 units hour
AND a.eventdatetime <= TO_DATE('01-02-2018 23:59:59','%m-%d-%Y %H:%M:%S')+5 units hour
AND a.agentid = 603

Open in new window

0
OMC2000Commented:
So, agentid is ID of an agent and each day we could have many groups of records for the same agent, but different calls.
If we can't ditinguish between call sessions we could exclude other records of the same agent between event type 1 and 7 like the following:
select d1.eventdatetime, d2.eventdatetime, (d2.eventdatetime - d1.eventdatetime)::interval second(6) to fraction
from AgentStateDetail d1 inner join AgentStateDetail d2 on d1.agentid = d2.agentid
and d1.eventtype=1 and d2.eventtype=7
where not exists (select 1 from AgentStateDetail d3 where d3.agentid = d2.agentid
and d3.eventtype=1 and d3.eventdatetime > d1.eventdatetime and d3.eventdatetime < d2.eventdatetime)
and 
not exists (select 1 from AgentStateDetail d4 where d4.agentid = d2.agentid
and d4.eventtype=7 and d4.eventdatetime > d1.eventdatetime and d4.eventdatetime < d2.eventdatetime)

Open in new window

0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Ryan SimmonsBusiness Analyst IIIAuthor Commented:
This is the solution:

Select b.agentId, 
   b.eventtype,
   b.eventdatetime start,
   e.eventdatetime end,
   b.eventtype,
   b.reasoncode,
   e.eventdatetime - b.eventdatetime ElapsedTime
From agentstatedetail b
    left join agentstatedetail e
         on e.agentid = b.agentid
            and e.eventdatetime =
                (Select Min(eventdatetime)
                 from agentstatedetail 
                 where agentid = b.agentid
                     and eventdatetime > b.eventdatetime)
WHERE b.eventdatetime >= TO_DATE('01-02-2018 00:00:00','%m-%d-%Y %H:%M:%S')+5 units hour
AND b.eventdatetime <= TO_DATE('01-02-2018 23:59:59','%m-%d-%Y %H:%M:%S')+5 units hour
AND b.agentid = 603

Open in new window


I found it here: https://stackoverflow.com/questions/30380653/sql-find-time-duration-duration-with-only-eventstarttime-query
0
PortletPaulEE Topic AdvisorCommented:
Recent versions of Informix supports "analytic"  and "window" functions which will most likely make this task far more efficient. As I don't have access to Informix the following example is in Postgres 9.6 but it may be of some help.
see LEAD/LAG
Note in Postgres using "extract(epoch from ...)" enables the query to return milliseconds
select
       agentid
     , eventdatetime
     , eventtype
     , '' State
     , extract(epoch from eventdatetime)
      - extract(epoch from 
                lag(eventdatetime,1) over(partition by agentid 
                                          order by eventdatetime)
               ) ElapsedTime
     , reasoncode
from agentstatedetail 
order by agentid, eventdatetime
;

Open in new window

The results from that is:
| agentid |        eventdatetime | eventtype | state | elapsedtime | reasoncode |
|---------|----------------------|-----------|-------|-------------|------------|
|     195 | 2013-01-21T19:38:25Z |         1 |       |      (null) |          0 |
|     195 | 2013-01-21T19:38:25Z |         2 |       |           0 |      32760 |
|     195 | 2013-01-21T19:43:37Z |         3 |       |         312 |          0 |
|     195 | 2013-01-21T19:44:14Z |         4 |       |          37 |          0 |
|     195 | 2013-01-21T19:44:15Z |         5 |       |           1 |          0 |
|     195 | 2013-01-21T19:45:56Z |         3 |       |         101 |          0 |
|     195 | 2013-01-21T20:12:36Z |         2 |       |        1600 |          0 |
|     195 | 2013-01-21T20:12:42Z |         7 |       |           6 |          0 |
|     296 | 2013-01-24T23:29:23Z |         1 |       |      (null) |          0 |
|     296 | 2013-01-24T23:29:23Z |         2 |       |           0 |      32760 |
|     296 | 2013-01-24T23:30:16Z |         3 |       |          53 |          0 |
|     296 | 2013-01-24T23:47:12Z |         7 |       |        1016 |          0 |
|     296 | 2013-01-24T23:47:34Z |         1 |       |          22 |          0 |
|     296 | 2013-01-24T23:47:34Z |         2 |       |           0 |      32760 |

Open in new window

nb: This isn't exactly the same as the result from the query you provided.  e.g. You could reverse the calculation and use LAG() instead of LEAD().

One other thing you should note. A timestamp column is accurate to (at least) milliseconds (not sure of the exact precision in Informix) but what this means is you should NEVER use "23:59:59" to indicate the end of a period :: because that period will be 1 second short

WHERE b.eventdatetime >= TO_DATE('01-02-2018','%m-%d-%Y')+5 units hour
AND b.eventdatetime < TO_DATE('01-03-2018','%m-%d-%Y')+5 units hour --<< use LESS THAN beginning of the next period
AND b.agentid = 603

CREATE TABLE agentstatedetail 
    ("agentid" int, "eventdatetime" timestamp, "gmtoffset" int, "eventtype" int, "reasoncode" int, "profileid" int)
;
  
INSERT INTO agentstatedetail 
    ("agentid", "eventdatetime", "gmtoffset", "eventtype", "reasoncode", "profileid")
VALUES
    (195, '2013-01-21 19:38:25', 0, 1, 0, 1),
    (195, '2013-01-21 19:38:25', 0, 2, 32760, 1),
    (195, '2013-01-21 19:43:37', 0, 3, 0, 1),
    (195, '2013-01-21 19:44:14', 0, 4, 0, 1),
    (195, '2013-01-21 19:44:15', 0, 5, 0, 1),
    (195, '2013-01-21 19:45:56', 0, 3, 0, 1),
    (195, '2013-01-21 20:12:36', 0, 2, 0, 1),
    (195, '2013-01-21 20:12:42', 0, 7, 0, 1),
    (296, '2013-01-24 23:29:23', 0, 1, 0, 1),
    (296, '2013-01-24 23:29:23', 0, 2, 32760, 1),
    (296, '2013-01-24 23:30:16', 0, 3, 0, 1),
    (296, '2013-01-24 23:47:12', 0, 7, 0, 1),
    (296, '2013-01-24 23:47:34', 0, 1, 0, 1),
    (296, '2013-01-24 23:47:34', 0, 2, 32760, 1)
;

Open in new window

see it operating at: http://sqlfiddle.com/#!17/535bd/1
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
OMC2000Commented:
Ryan, in any case,  your statement won't work in general. It could return correct result for only one call in specified period. All other calls will be ignored
0
Ryan SimmonsBusiness Analyst IIIAuthor Commented:
Thanks guys. I have a functioning query that is returning the results I need.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Databases

From novice to tech pro — start learning today.