Transact-SQL - 直到满足条件的数字行

MRa*_*amL 7 t-sql sql-server count row-number reset

我正在尝试在"x"列中生成数字,考虑字段"eq"中的值,以便它应该为每个记录设置一个数字,直到它满足值"1",并且下一行应该重置并再次开始计数.我尝试过使用row_number,但问题是我只需要在我需要评估的列中使用1和0,而我使用row_number看到的情况是在列中使用增长值.也尝试了排名,但我没有设法让它工作.

nInd    Fecha       Tipo    @Inicio     @contador_I  @Final     @contador_F eq  x
1       18/03/2002  I       18/03/2002  1            null       null        0   1
2       20/07/2002  F       18/03/2002  1            20/07/2002 1           1   2
3       19/08/2002  I       19/08/2002  2            20/07/2002 1           0   1
4       21/12/2002  F       19/08/2002  2            21/12/2002 2           1   2
5       17/03/2003  I       17/03/2003  3            21/12/2002 2           0   1
6       01/04/2003  I       17/03/2003  4            21/12/2002 2           0   2
7       07/04/2003  I       17/03/2003  5            21/12/2002 2           0   3
8       02/06/2003  F       17/03/2003  5            02/06/2003 3           0   4
9       31/07/2003  F       17/03/2003  5            31/07/2003 4           0   5
10      31/08/2003  F       17/03/2003  5            31/08/2003 5           1   6
11      01/09/2005  I       01/09/2005  6            31/08/2003 5           0   1
12      05/09/2005  I       01/09/2005  7            31/08/2003 5           0   2
13      31/12/2005  F       01/09/2005  7            31/12/2005 6           0   3
14      14/01/2006  F       01/09/2005  7            14/01/2006 7           1   4
Run Code Online (Sandbox Code Playgroud)

Eoi*_*inS 5

还有另一种解决方案:

select 
  nind, eq, row_number() over (partition by s order by s) 
from (
  select 
    nind, eq, coalesce((
      select sum(eq) +1 from mytable pre where pre.nInd < mytable.nInd)
    ,1) s --this is the sum of eq!
  from mytable) g
Run Code Online (Sandbox Code Playgroud)

内部子查询groups1in 的每次出现顺序创建eq。然后我们可以使用row_number() over partition来获取我们的计数器。

这是一个使用 Sql Server的示例