Row_Number()超过分区查询

Tri*_*ire 2 sql t-sql

我有以下查询:

declare @temp1 table
(ID1 int not null,
 ID2 int not null)

set nocount off

insert into @temp1 values(1453,931)
insert into @temp1 values(1454,931)
insert into @temp1 values(1455,931)

insert into @temp1 values(2652,1101)
insert into @temp1 values(2653,1101)
insert into @temp1 values(2654,1101)
insert into @temp1 values(2655,1101)
insert into @temp1 values(2656,1101)

insert into @temp1 values(3196,1165)

insert into @temp1 values(3899,1288)
insert into @temp1 values(3900,1288)
insert into @temp1 values(3901,1288)
insert into @temp1 values(3902,1288)

--select * from @temp1

select ID1,ID2, ROW_NUMBER() over(partition by ID2 order by ID1) as RowNum1
from @temp1
Run Code Online (Sandbox Code Playgroud)

我现在要做的是创建一个新列,将所有ID2组合在一起..具有931的ID2应该在新列中具有值1,1101应该具有2,1165应该是3并且最终所有1288应该具有4. ..请问我可以得到帮助吗?

Tec*_*hDo 8

您可以DENSE_RANK()用来获得结果.它返回结果集分区内的行级别,排名中没有任何间隙.行的等级是一行加上有关行之前的不同等级的数量.有关更多详细信息,请参阅链接DENSE_RANK(Transact-SQL).请试试:

select ID1, ID2, DENSE_RANK() over(order by ID2) as RowNum1
from @temp1
Run Code Online (Sandbox Code Playgroud)