我有以下查询:

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

我现在想做的是创建一个新列,将所有ID2分组在一起。例如,具有931的ID2在新列中的值应该为1,1101应该具有2,1165应该为3,最后所有1288应该具有4。 ..请问能帮我吗?

最佳答案

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

select ID1, ID2, DENSE_RANK() over(order by ID2) as RowNum1
from @temp1

关于sql - Row_Number()通过分区查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/14352472/

10-10 21:43