I have a table that reflects events for customers - a customer has
different event types registered along with event time.
...
I need to show customers and when their process was started and ended,
as you could see not necessarily all are ended and some can be
started/ended several times
M.G. (michael@gurfinkel.us) writes:
I have a table that reflects events for customers - a customer has different event types registered along with event time.
...
I need to show customers and when their process was started and ended,
as you could see not necessarily all are ended and some can be started/ended several times
Here is a solution:
; WITH intervals AS (
SELECT a.CUST_ID, a.ETIME, b.ENDED
FROM @T a
OUTER APPLY (SELECT MIN(b.ETIME) AS ENDED
FROM @T b
WHERE b.CUST_ID = a.CUST_ID
AND b.ETIME > a.ETIME
AND b.EVENT_ID = 2) AS b
WHERE a.EVENT_ID = 1
)
SELECT CUST_ID, MIN(ETIME) AS STARTED, ENDED
FROM intervals
GROUP BY CUST_ID, ENDED
ORDER BY CUST_ID, STARTED
The MIN(ETIME) is there for the case there are multiple rows with EVENT_ID = 1 after each other.
--
Erland Sommarskog, Stockholm, esquel@sommarskog.se
Sysop: | Keyop |
---|---|
Location: | Huddersfield, West Yorkshire, UK |
Users: | 112 |
Nodes: | 8 (1 / 7) |
Uptime: | 17:47:06 |
Calls: | 2,468 |
Files: | 8,621 |
Messages: | 1,890,725 |