T-SQL incrementing counter based on change in a column value

无人久伴 提交于 2019-11-28 13:11:17

In SQL Server 2012 and later, you have the luxury of 1) analytic functions, and 2) running totals:

declare @t table (
    Id int primary key,
    Value int not null
);

insert into @t (Id, Value)
values
(1, 3),
(2, 3),
(3, 2),
(4, 2),
(5, 2),
(6, 3),
(7, 0),
(8, 0);

select sq.Id, sq.Value,
    sum(case when sq.pVal = sq.Value then 0 else 1 end) over(order by sq.Id) as [Counter]
from (
    select t.Id, t.Value, lag(t.Value, 1, null) over(order by t.Id) as [pVal]
    from @t t
) sq
order by sq.Id;

Also, this solution does not depend on ID column having no gaps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!