2015-04-01 65 views
-1

我有下面的樣本表。該表按另一列未顯示進行排序。我需要根據值列中的變化來增加計數器列值。請看下面的例子。這怎麼能在T-SQL(SQL Server 2014)中完成。基於列值的變化的T-SQL遞增計數器

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

預期輸出:

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 

回答

4

在SQL Server 2012及更高版本,你有1)解析函數的奢侈品,和2)運行總計:

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; 

而且,這解決方案不依賴於沒有間隙的列。

+0

謝謝。有效。 – sqlnewbie 2015-04-03 02:01:17