DROP TABLE IF EXISTS #Groups;
CREATE TABLE #Groups
(
[entity] nvarchar(30),
[workItem] nvarchar(255),
[CreatedDate] datetime
)
INSERT INTO #Groups ([entity], [workItem], [CreatedDate])
VALUES
( N'5002', N'AG', N'2020-09-04T13:24:00.823' ),
( N'5002', N'AG', N'2020-09-04T13:23:05.103' ),
( N'5002', N'AG', N'2020-09-04T14:23:05.103' ),
( N'5002', N'SH', N'2020-09-04T13:26:42.367' ),
( N'5002', N'SH', N'2020-09-04T13:27:17.25' ),
( N'5003', N'SH', N'2020-10-04T15:36:42.367' ),
( N'5003', N'SH', N'2020-10-04T15:37:17.25' );
Expected result:
entity workItem CreatedDate
--------------------------------------------
5002 AG 2020-09-04 13:24:00.823
5002 AG 2020-09-04 14:23:05.103
5002 SH 2020-09-04 13:27:17.250
5003 SH 2020-10-04 15:37:17.250
Basically, I need to group by entity, workitem and date with a one-minute tolerance.
Here is my attempt (though I didn't go too far):
SELECT
t1.entity,
t1.workItem,
t1.CreatedDate,
LAG(t1.CreatedDate, 1) OVER (PARTITION BY t1.entity, t1.workItem ORDER BY t1.CreatedDate) AS CreateDate_new
FROM
#Groups t1
LEFT JOIN
#Groups t2 ON t2.entity = t1.entity
AND t2.workItem = t1.workItem
AND t2.CreatedDate >= t1.CreatedDate
AND (DATEDIFF(MINUTE, t1.CreatedDate, t2.CreatedDate) < 1)
GROUP BY
t1.entity, t1.workItem, t1.CreatedDate
ORDER BY
t1.workItem