输入
ID
12345
12346
12346
12387
12568
12387
12387
输出
ID - Value
12345 - 1
12346 - 2
12346 - 2
12387 - 3
12568 - 4
12387 - 5
12387 - 5
我有一个如上所示的输入,我还需要显示一个输出。
所以看一下,输出应该是这样的,如果前一个值与当前值相同,则值不应该发生变化,而如果值发生变化,则该值应该递增。 第一个值是默认值“1”。
SQL server 2008及以上可以写吗? 这个有什么特殊功能吗??
我们可以在 SSIS 中编写相同的代码吗? 哪一个容易完成?
最佳答案
如果性能不是关键约束使用这个
declare @Id as int, @Rownumber as int = 0
declare @tempTable table (Id int, Rownumber int)
declare tempCur cursor for
select Id from yourtable
OPEN tempCur
FETCH NEXT FROM tempCur
INTO @Id
WHILE (@@FETCH_STATUS=0)
begin
declare @tempId as int
select @tempId=id from @tempTable where Rownumber=(select max(Rownumber) from @tempTable)
if (@tempId = @Id)
insert into @tempTable select @Id,@Rownumber
else
begin
set @Rownumber = @Rownumber+1
insert into @tempTable select @Id,@Rownumber
end
FETCH NEXT FROM tempCur
INTO @Id
end
select * from @tempTable
CLOSE tempCur
DEALLOCATE tempCur
供您引用:
关于sql-server - 用于递增的 SQL Server 或 SSIS 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30717806/