Sql server 基于事件的数据编号

Sql server 基于事件的数据编号,sql-server,relational-database,Sql Server,Relational Database,我需要帮助根据特定值的出现对数据进行编号 让我们考虑输入 Col1 Col2 1 a 2 1 3 2 4 3 5 a 6 1 7 4 8 a 9 2 10 3 我想根据col2中出现的“a”对它们进行编号。输出应该如下所示 Col1 Col2 Result 1 a 1 2 1 1 3 2 1 4 3 1 5 a 2 6 1 2 7 4 2 8 a 3 9 2 3 10

我需要帮助根据特定值的出现对数据进行编号

让我们考虑输入

Col1    Col2
1   a
2   1
3   2
4   3
5   a
6   1
7   4
8   a
9   2
10  3
我想根据col2中出现的“a”对它们进行编号。输出应该如下所示

Col1    Col2    Result
1   a   1
2   1   1
3   2   1
4   3   1
5   a   2
6   1   2
7   4   2
8   a   3
9   2   3
10  3   3
您可以使用光标

1) Create a temp table
2) Output the result to a cursor
3) Loop throught the cursor and update the temp table
4) Select from the temp table. 
编辑:

我不知道这有多有用,但这句话不用光标就能得到你想要的东西

SELECT [Col1]
      ,[Col2]
      , (select count(*) from Table_1 where Col2 = 'a' and Col1 <= t1.Col1) 
  FROM [Table_1] t1 
您可以使用光标

1) Create a temp table
2) Output the result to a cursor
3) Loop throught the cursor and update the temp table
4) Select from the temp table. 
编辑:

我不知道这有多有用,但这句话不用光标就能得到你想要的东西

SELECT [Col1]
      ,[Col2]
      , (select count(*) from Table_1 where Col2 = 'a' and Col1 <= t1.Col1) 
  FROM [Table_1] t1 

需要注意的是,在SQL Server 2012中,您可以使用累计总和来完成此操作:

select col1, col2,
       sum(case when col2 = 'a' then 1 else 0 end) over (order by col1) as result
from t;

其他支持窗口/分析功能的数据库也支持累积和。

请注意,在SQL Server 2012中,您可以使用累积和执行此操作:

select col1, col2,
       sum(case when col2 = 'a' then 1 else 0 end) over (order by col1) as result
from t;

其他支持窗口/分析功能的数据库也支持累积和。

数据没有顺序,只有在查询中明确指定的顺序。因此1-4、5-7和8-10是逻辑组,您想按这些组排序吗?是,a的第一次出现在结果中的值应为1,并且在第二次出现“a”之前应保持不变。根据col2Data中出现的“a”增加结果值没有顺序,查询中明确指定的顺序除外。因此1-4、5-7和8-10是逻辑组,您想按这些组排序吗?是的,第一次出现的a在结果中应该有值1,并且在第二次出现“a”之前应该保持不变。根据COL2TANK you中出现的“a”增加结果值,但我希望在查询中完成此操作,而不是使用PL/SQL块。如果这有帮助,我已修改了我的答案。谢谢,通过一些小更改,我可以将其用于我的需求。谢谢,但我希望在查询中完成此操作,不使用PL/SQL块。如果这有帮助,我已经修改了我的答案。谢谢,只要稍作修改,我就可以将其用于我的需求。谢谢。它帮助了我,谢谢你。这对我很有帮助,解析函数更简单。谢谢。用解析函数就简单多了。非常感谢。