Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

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

I have sample table like below. The table is sorted by another column that is not shown. I need to increment a counter column value based on whenever there is change in the value column. Please see below for an example. How can this be done in T-SQL (SQL Server 2014).

ID Value
1  3
2  3
3  2
4  2
5  2
6  3
7  0
8  0

Expected Output:

ID Value Counter
1  3     1
2  3     1
3  2     2
4  2     2
5  2     2
6  3     3
7  0     4
8  0     4
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...