如何依赖SQL Server

时间:2017-08-18 14:48:48

标签: sql-server-2016

我试图找出如何根据不同列中值的变化进行自动增量,如下所示

这就是我现在所得到的

OtherID | AUTOINCREMENT
--------+---------------
A       | 1
A       | 2 
B       | 3
C       | 4
D       | 5
D       | 6

这是我所希望的

OtherID | AUTOINCREMENT
--------+---------------
A       | 1
A       | 1 
B       | 2
C       | 3
D       | 4
D       | 4

2 个答案:

答案 0 :(得分:0)

这将是SQL Server中的Windows函数

select
   OtherID,
   row_number() over (partition by OtherID order by OtherID) as AutoIncrement
from
   SomeTable

order by OtherID在这里工作假设你的OtherID就是你所说的......一个以A开头并向上移动字母的字符。否则,您可以将其替换为(select null)

select
   OtherID,
   row_number() over (partition by OtherID order by (select null)) as AutoIncrement
from
   SomeTable

修改

select
   OtherID,
   dense_rank() over (order by cast(left(OtherID,len(OtherID) - 1) as int)) as AutoIncrement
from
   SomeTable

答案 1 :(得分:0)

试试这个 使用row_number()

select Row_number() over(partition by OtherID  order by
 (select 1)),AUTOINCREMENT from mytable