Если я понимаю ваш вопрос, следующий подход может помочь.Просто используйте SUM()
в качестве оконной функции и ROW_NUMBER()
.
Таблица:
CREATE TABLE #Data (
Ident int,
Name varchar(10),
Length int,
Width int,
[Function] int,
[Date] datetime
)
INSERT INTO #Data
(Ident, Name, Length, Width, [Function], [Date])
VALUES
(12345, 'Name1', 2500, 1000, 1, '2019-06-13T22:13:26.197'),
(12345, 'Name1', 2500, 1000, 1, '2019-06-13T22:16:21.950'),
(12345, 'Name1', 2500, 1000, 2, '2019-06-13T22:17:49.753'),
(12345, 'Name1', 2500, 1000, 2, '2019-06-13T22:18:28.807'),
(12345, 'Name1', 2500, 1000, 1, '2019-06-13T22:19:25.433'),
(12345, 'Name1', 2500, 1000, 2, '2019-06-13T22:30:41.243'),
(12345, 'Name1', 2500, 1000, 1, '2019-06-13T22:34:04.517'),
(12345, 'Name1', 2500, 1000, 1, '2019-06-13T22:38:53.967'),
(98765, 'Name2', 2500, 1000, 1, '2019-06-13T22:58:15.027'),
(98765, 'Name2', 2500, 1000, 2, '2019-06-13T23:01:09.607'),
(98765, 'Name2', 2500, 1000, 1, '2019-06-13T23:04:20.060'),
(98765, 'Name2', 2500, 1000, 1, '2019-06-13T23:07:27.970'),
(98765, 'Name2', 2500, 1000, 2, '2019-06-13T23:21:09.703')
Оператор:
SELECT
t.Ident, t.Name, t.Length, t.Width, t.[Function], t.[Date]
FROM (
SELECT
*,
SUM(CASE
WHEN [Function] = 1 THEN 1
WHEN [Function] = 2 THEN -1
ELSE 0
END) OVER (PARTITION BY Ident, Name, Length, Width) AS Cnt,
ROW_NUMBER() OVER (PARTITION BY Ident, Name, Length, Width ORDER BY [Date]) AS Rn
FROM #Data
) t
WHERE t.Rn <= t.Cnt
Вывод:
Ident Name Length Width Function Date
12345 Name1 2500 1000 1 13/06/2019 22:13:26
12345 Name1 2500 1000 1 13/06/2019 22:16:21
98765 Name2 2500 1000 1 13/06/2019 22:58:15