2

我有以下查询:

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 组合在一起。即 ID2 的 931 在新列中应该有值 1,1101 应该有 2,1165 应该是 3,最后所有 1288 应该有 4。 .. 我可以得到帮助吗?

4

1 回答 1

8

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

select ID1, ID2, DENSE_RANK() over(order by ID2) as RowNum1
from @temp1
于 2013-01-16T06:31:31.097 回答