You can use this query ( here ):
DECLARE @Results TABLE( RowNum INT NOT NULL, senderID INT NOT NULL DEFAULT(80), recipientID INT NOT NULL DEFAULT(79), PRIMARY KEY(RowNum,senderID,recipientID), messageTime DATETIME NOT NULL ); INSERT INTO @Results(RowNum,senderID,recipientID,messageTime) SELECT ROW_NUMBER() OVER(PARTITION BY senderID,recipientID ORDER BY messageTime, ID) AS RowNum, c.senderID,c.recipientID,c.messageTime FROM dbo.tbl_chatMessages c; WITH RecursiveCTE AS( SELECT crt.RowNum,crt.senderID,crt.recipientID, crt.messageTime, 1 AS SessionID FROM @Results crt WHERE crt.RowNum=1 UNION ALL SELECT crt.RowNum,crt.senderID,crt.recipientID, crt.messageTime, CASE WHEN DATEDIFF(MINUTE,prev.messageTime,crt.messageTime) <= 10 THEN prev.SessionID ELSE prev.SessionID+1 END FROM @Results crt INNER JOIN RecursiveCTE prev ON crt.RowNum=prev.RowNum+1 AND crt.senderID=prev.senderID AND crt.recipientID=prev.recipientID ) SELECT *, STUFF(CONVERT(VARCHAR(8), DATEADD(SECOND,x.SessionDuration,0), 114), 1,3,'') AS SessionDuration_mmss, SUM(x.SessionDuration) OVER() AS SessionDuration_Overall, STUFF(CONVERT(VARCHAR(8), DATEADD(SECOND,SUM(x.SessionDuration) OVER(),0), 114), 1,3,'') AS SessionDuration_Overall_mmss FROM( SELECT r.senderID,r.recipientID,r.SessionID, DATEDIFF(SECOND, MIN(r.messageTime),MAX(r.messageTime)) AS SessionDuration FROM RecursiveCTE r GROUP BY r.senderID,r.recipientID,r.SessionID ) x OPTION(MAXRECURSION 0);
Results:
senderID recipientID SessionID SessionDuration SessionDuration_mmss SessionDuration_Overall SessionDuration_Overall_mmss -------- ----------- ----------- --------------- -------------------- ----------------------- ---------------------------- 80 79 1 97 01:37 140 02:20 80 79 2 43 00:43 140 02:20