开发者

Select numbered list of duplicate entries

Really simple example:

Let's say I have this table:

ID         Name
GUID1      John
GUID2      John
GUID3      John
GUID4      John
GUID5      Jane
GUID6      Jane

I would like to do a select which assigns a counter to every occurence of the same name (starting at 1 each time). i.e.:

ID         Name     Counter
GUID1      John     1
GUID2      John     2
GUID3      John     3
GUID4      John     4
GUID5      Jane     1
GUID6      Jane     2

So that the key (Name, Counter) forms a uni开发者_StackOverflow社区que combination.

Thanks

Karl


declare @T table(ID varchar(10), Name varchar(10))
insert into @T values
('GUID1',      'John'),
('GUID2',      'John'),
('GUID3',      'John'),
('GUID4',      'John'),
('GUID5',      'Jane'),
('GUID6',      'Jane')

select
  ID,
  Name,
  row_number() over(partition by Name order by ID) as Counter
from @T
order by ID
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜