当位列更改时,SQL Server 2012需要增加序列号

时间:2015-12-13 12:52:17

标签: sql sql-server tsql sql-server-2012 lag

我有一张这样的表:

dDate            amount sigma  
-----------------------------
2015-01-01         0,00     1  
2015-11-01       150,00     0  
2015-11-10        25,00     0  
2015-11-11      1028,90     0  
2015-11-12       878,90     1  
2015-11-15       150,00     0  
2015-12-13       723,90     1  

每次sigma列更改时,我都需要增加一个序列号,所以这应该是结果:

dDate            Amount sigma  seqNr
------------------------------------
2015-01-01         0,00     1      0
2015-11-01       150,00     0      1
2015-11-10        25,00     0      1
2015-11-11      1028,90     0      1
2015-11-12       878,90     1      2
2015-11-15       150,00     0      3
2015-12-13       723,90     1      4

我应该使用lag功能吗?

谢谢

2 个答案:

答案 0 :(得分:3)

似乎您想要计算任何给定值的" 1" s。 (这假设第一个值应该是" 1"在您的示例中。)在SQL Server 2012+中,您可以使用累积总和来执行此操作:

select t.*,
       sum(case when sigma = 1 then 1 else 0 end) over (order by ddate)
from t;

实际上,如果sigma仅取0和1,您可以将其简化为:

select t.*,
       sum(cast(sigma as int)) over (order by ddate)
from t;

如果您想要实际更改(1 - > 0或0 - > 1),则滞后和累积总和会有所帮助:

select t.*,
       sum(inc) over (order by ddate) 
from (select t.*,
             (case when sigma <> lag(sigma) over (order by ddate) then 1
                   else 0 end) as inc
      from t
     ) t;

答案 1 :(得分:0)

这是不同的变量名称,但同样的事情
和戈登一样,但绝对不是案例 - 以为我可以一次性做到这一点

  select *, sum(inc) over (order by [ID]) as seq 
  from 
  (   SELECT [ID], [OnOff]
           , isnull(abs(cast(OnOff as int) - lag(cast(OnOff as int)) over (order by [ID])),0) as inc
      FROM [test].[dbo].[Table_2]
  ) tt