0

world.

I'm try to find a way to compile multiple events together. Data looks like this:

Existing Data

Basically, it is series of row data with event logs

I want to generate an aggregation of these row events such that if a new event occurred within 30 seconds of the other ending, it combines the time together. However, if the event log does not have an abutting event, then it is not captured. And these events are 'person' specific.

I envision the output to look something like this:

Output data

My intuition suggests using some kind of while loop, but I'm not sure where to start

0

2 Answers 2

2

There's no need for recursion (and very hard to write) or a loop over a cursor.

SELECT Person, Min(starttime), Max(starttime), -- get a concatenated string Trim(Trailing ',' FROM (XmlAgg(Reason || ',' ORDER BY Reason ) (VARCHAR(1000)))) FROM ( SELECT Person, Start_timestamp, Stop_timestamp, Reason, -- assign the same number to all rows within 30 seconds Sum(flag) Over Over (PARTITION BY Person ORDER BY Start_timestamp ROWS Unbounded Preceding) AS grp FROM ( SELECT Person, Start_timestamp, Stop_timestamp, Reason, -- check if previous end is within 30 seconds of the current start CASE WHEN Lag(Stop_timestamp) Over (PARTITION BY Person ORDER BY Start_timestamp) + INTERVAL '30' SECOND < Start_timestamp THEN 0 ELSE 1 END AS flag FROM tab ) AS dt ) AS dt -- aggregate per person and group GROUP BY Person, grp 

If your Teradata version supports SESSIONIZE you can simplify the group calculation, but I couldn't write this syntaxc ad hoc :-)

Sign up to request clarification or add additional context in comments.

1 Comment

This works pretty close to what I'm hoping for. Thank you dnoeth.
0

You can achieve this using RECURSIVE CTE

WITH RECURSIVE MYREC(Person,Start_timestamp,Stop_timestamp ,Reason,LVL) AS( SELECT Person,MIN(Start_timestamp),MAX(Stop_timestamp),MIN(Reason)(varchar(100)) AS Reason,1 FROM MYTABLE GROUP BY 1 UNION ALL SELECT b.Person,b.Start_timestamp,b.Stop_timestamp ,trim(a.Reason) || ',' || trim( b.Reason), LVL+1 FROM MYTABLE a INNER JOIN MYREC b ON a.Person = b.Person AND a.Reason > b.Reason ) SELECT Person,Start_timestamp,Stop_timestamp,Reason FROM MYREC QUALIFY RANK() OVER(PARTITION BY Person ORDER BY Reason DESC) = 1 

Change MYTABLE to your tablename

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.