Вам нужно разделить на Property
и CommunicationType
:
Таблица:
CREATE TABLE #Data (
ActivityID int,
Property varchar(100),
[DATE] date,
CommunicationType varchar(10)
)
INSERT INTO #Data
(ActivityID, Property, [DATE], CommunicationType)
VALUES
(1046, 'Red Property', '20191030', 'field'),
(10467, 'Red Property', '20191029', 'field'),
(10591, 'Red Property', '20191028', 'calls'),
(10971, 'Blue Property', '20191027', 'field'),
(10971, 'Blue Property', '20191026', 'field'),
(10971, 'Blue Property', '20191026', 'calls'),
(10965, 'Green Property', '20191024', 'calls'),
(10765, 'Green Property', '20191023', 'calls'),
(10765, 'Green Property', '20191019', 'field'),
(10765, 'Green Property', '20191015', 'field'),
(10765, 'Green Property', '20191012', 'field')
Заявление:
SELECT
*,
CASE
WHEN CommunicationType = 'field' THEN DENSE_RANK() OVER (PARTITION BY Property, CommunicationType ORDER BY [DATE] ASC)
ELSE NULL
END AS Rank
FROM #Data
Результат:
ActivityID Property DATE CommunicationType Rank
10971 Blue Property 2019-10-26 calls NULL
10971 Blue Property 2019-10-26 field 1
10971 Blue Property 2019-10-27 field 2
10765 Green Property 2019-10-23 calls NULL
10965 Green Property 2019-10-24 calls NULL
10765 Green Property 2019-10-12 field 1
10765 Green Property 2019-10-15 field 2
10765 Green Property 2019-10-19 field 3
10591 Red Property 2019-10-28 calls NULL
10467 Red Property 2019-10-29 field 1
1046 Red Property 2019-10-30 field 2