Это можно сделать с помощью простого exists
:
Сначала создайте и заполните таблицу образцов ( Пожалуйста сохраните этот шаг в своих будущих вопросах)
DECLARE @T As Table (
[client] int,
[datetime] datetime,
[col1] varchar(6),
[col2] varchar(5)
);
INSERT INTO @T ([client], [datetime], [col1], [col2]) VALUES
(1, '2019-05-20T14:30:08', NULL, 'Green'),
(1, '2019-05-31T12:23:55', 'Yellow', NULL),
(1, '2019-05-31T13:00:08', NULL, 'Green'),
(2, '2019-09-10T12:22:17', 'Yellow', NULL),
(2, '2019-09-10T13:30:57', NULL, 'Green'),
(3, '2019-09-14T07:34:41', 'Red', NULL),
(3, '2019-09-13T07:45:24', 'Yellow', NULL),
(4, '2019-01-15T14:15:08', 'Yellow', NULL),
(4, '2019-01-15T14:48:40', NULL, 'Green'),
(5, '2019-06-24T16:13:29', NULL, 'Green'),
(5, '2019-06-25T13:14:07', 'Yellow', NULL),
(6, '2019-09-06T11:22:19', 'Yellow', NULL),
(6, '2019-09-06T12:19:48', NULL, 'Green'),
(6, '2019-10-08T12:19:08', 'Red', NULL);
Затем оператор удаления:
DELETE t1
FROM @T AS t1
WHERE t1.col1 = 'Yellow'
AND EXISTS
(
SELECT 1
FROM @T t2
WHERE t2.[datetime] > t1.[datetime]
AND t2.[datetime] <= DATEADD(HOUR, 24, t1.[datetime])
AND t2.[client] = t1.[client]
AND (
t2.[col2] IS NOT NULL
OR t2.[col1] <> 'Yellow'
)
)
Демонстрационная версия