更新时间:2023-02-05 18:29:47
试试这个:
SELECT CustomerID, YearMonth, True_False,
CASE
WHEN True_False = 1 THEN 0
ELSE ROW_NUMBER() OVER (PARTITION BY True_False, grp
ORDER BY YearMonth)
END AS Sequence
FROM (
SELECT CustomerID, YearMonth, True_False,
ROW_NUMBER() OVER (ORDER BY YearMonth) -
ROW_NUMBER() OVER (PARTITION BY True_False
ORDER BY YearMonth) AS grp
FROM mytable ) AS t
ORDER BY YearMonth
查询计算字段grp
,该字段标识具有相同True_False
值的连续记录的岛.在外部查询中使用此字段,我们可以枚举这些岛屿中包含的记录,从而获得所需的序列号.
The query calculates field grp
which identifies islands of consecutive records having the same True_False
value. Using this field in an outer query we can enumerate the records contained inside these islands and thus get the required sequence number.