I have two tables, DATA
and EVENTS
, with the following data:
EVENTS
EventIndex ObjID LocID EventData EventTime EventType
8
Something like this could get you started along nicely:
SQL Fiddle: http://www.sqlfiddle.com/#!2/6e6a7/33
SELECT d.TagValue AS Name,
d2.TagValue AS LOCATION,
e.eventTime AS Entry,
( SELECT eventtime
FROM EVENTS e2
WHERE e2.objID = e.objID
AND e2.eventTime > e.eventTime LIMIT 1) AS ExitTime,
(e.eventTime -
( SELECT eventtime
FROM EVENTS e2
WHERE e2.objID = e.objID
AND e2.eventTime > e.eventTime LIMIT 1)) AS TotalTime
FROM events e,
DATA d,
DATA d2
WHERE e.eventIndex = d.eventIndex
AND e.eventIndex = d2.eventIndex
AND d.TagName = "ObjName"
AND d2.TagName = "LocName"
AND mod(
( SELECT count(*)
FROM EVENTS e2
WHERE e2.objID = e.objID
AND e2.eventTime < e.eventTime),2) = 0
ORDER BY EventTime;
Result:
NAME LOCATION ENTRY EXITTIME TOTALTIME
John H118 May, 19 2013 11:32:11+0000 May, 19 2013 11:35:18+0000 -307
Peter H118 May, 19 2013 12:24:45+0000 May, 19 2013 12:32:18+0000 -773
I added extra events, to proof against an exit from one event being considered as an entry of another.
The above query can be optimized, if we say that an entry and exit cannot take place on different days e.g. USER enters 11.59PM and leaves 1.00AM...
SELECT d.TagValue AS Name,
d2.TagValue AS LOCATION,
e.eventTime AS Entry,
( SELECT eventtime
FROM EVENTS e2
WHERE e2.objID = e.objID
AND e2.eventTime > e.eventTime LIMIT 1) AS ExitTime,
(e.eventTime -
( SELECT eventtime
FROM EVENTS e2
WHERE e2.objID = e.objID
AND e2.eventTime > e.eventTime AND
DATE(e2.eventTime) = DATE(e.eventTime) LIMIT 1)) AS TotalTime
FROM events e,
DATA d,
DATA d2
WHERE e.eventIndex = d.eventIndex
AND e.eventIndex = d2.eventIndex
AND d.TagName = "ObjName"
AND d2.TagName = "LocName"
AND mod(
( SELECT count(*)
FROM EVENTS e2
WHERE e2.objID = e.objID
AND e2.eventTime < e.eventTime AND
DATE(e2.eventTime) = DATE(e.eventTime)),2) = 0
ORDER BY EventTime;
SQL Fiddle: http://www.sqlfiddle.com/#!2/6e6a7/35
This also assumes that each entry
must have an exit
, which is why I use the modulo operator.
All Even
events for a Object
are an entry, all Odd
events are an exit
.
For more conditions, obviously the query must be modified.
Update: Using SQL Lite (no mod but %)
SQLFiddle: http://www.sqlfiddle.com/#!7/6e6a7/4
SELECT d.TagValue AS Name,
d2.TagValue AS LOCATION,
e.eventTime AS Entry,
( SELECT eventtime
FROM EVENTS e2
WHERE e2.objID = e.objID
AND e2.eventTime > e.eventTime LIMIT 1) AS ExitTime,
(e.eventTime -
( SELECT eventtime
FROM EVENTS e2
WHERE e2.objID = e.objID
AND e2.eventTime > e.eventTime LIMIT 1)) AS TotalTime
FROM events e,
DATA d,
DATA d2
WHERE e.eventIndex = d.eventIndex
AND e.eventIndex = d2.eventIndex
AND d.TagName = "ObjName"
AND d2.TagName = "LocName"
AND (
( SELECT count(*)
FROM EVENTS e2
WHERE e2.objID = e.objID
AND e2.eventTime < e.eventTime)%2) = 0
ORDER BY EventTime;