Один из возможных подходов к получению результатов:
Введите:
CREATE TABLE #Table (
id int,
name varchar(10),
remarks varchar(50)
)
INSERT INTO #Table
(id, name, remarks)
VALUES
(1, 'text1', NULL),
(2, 'text2', 'anyRemarks'),
(3, 'text3', NULL),
(4, 'text4', 'anyRemarks'),
(5, 'text5', NULL),
(6, 'text6', NULL),
(7, 'text7', 'anyRemark')
Заявление:
SELECT
id,
name,
remarks,
CASE
WHEN remarks IS NULL THEN 0
ELSE ROW_NUMBER() OVER (PARTITION BY CASE WHEN remarks is NULL THEN 0 ELSE 1 END ORDER BY id)
END AS [Rn]
FROM #Table
ORDER BY id
Выход:
id name remarks Rn
1 text1 NULL 0
2 text2 anyRemarks 1
3 text3 NULL 0
4 text4 anyRemarks 2
5 text5 NULL 0
6 text6 NULL 0
7 text7 anyRemark 3