Dữ liệu mẫu
create table sometable([group] varchar(10), id int, somedata int)
insert sometable select 'Horses', 9, 11
insert sometable select 'chickens', 19, 121
insert sometable select 'Horses', 29, 123
insert sometable select 'chickens', 49, 124
insert sometable select 'Cows', 98, 1
insert sometable select 'Horses', 99, 2
Truy vấn
select
Record = ROW_NUMBER() over (order by [Group], id),
[Group],
GroupSequence = DENSE_RANK() over (order by [Group])
from sometable
Đầu ra
Record Group GroupSequence
-------------------- ---------- --------------------
1 chickens 1
2 chickens 1
3 Cows 2
4 Horses 3
5 Horses 3
6 Horses 3