2017-08-18 18 views
1

我试图找出如何做基于在不同的列值的变化自动递增如下图所示如何使用依赖于列在SQL Server中执行自动递增

这就是我现在越来越

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 
+0

你有什么期望得到A,A,B,A ? 1,1,2,1或1,1,2,3? – user3012759

回答

0

这是SQL Server在Windows功能

​​

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 
+0

感谢您的回复。我试过你的代码(选择null),因为'otherId'列不是字母表,它仍然不能正常工作。以下是otherId列的确切值。它以1H,2H,2H,3H .... 100H,101H开始。所以在这种情况下,我想增量值是1,2,2,3 ...等 – Rbird

+0

该值仍然会基于分区增加,但这个增量的顺序很难,因为你是混合数字和字符数据 – scsimon

+0

@Rbird根据您的新信息查看编辑。这就是为什么准确的测试数据如此重要... – scsimon

0

试试这个 使用row_number()

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