34,591
社区成员
发帖
与我相关
我的任务
分享
if object_id('tb') is not null drop table tb
go
create table tb([ID] int,[Name] varchar(10))
insert tb select 1,'A'
union all select 2,'B'
union all select 3,'C'
union all select 4,'A'
union all select 5,'B'
union all select 6,'C'
union all select 7,'B'
union all select 8,'B'
union all select 9,'C'
go
select xh=(select count(1) from tb where name=a.name and id<a.id )+1,name from tb a order by name,xh
drop table tb
/*
xh name
----------- ----------
1 A
2 A
1 B
2 B
3 B
4 B
1 C
2 C
3 C
(所影响的行数为 9 行)
*/
if object_id('tb') is not null drop table tb
go
create table tb([ID] int,[Name] varchar(10))
insert tb select 1,'A'
union all select 2,'B'
union all select 3,'C'
union all select 4,'A'
union all select 5,'B'
union all select 6,'C'
union all select 7,'B'
union all select 8,'B'
union all select 9,'C'
go
select 序号=rank() over(partition by name order by id),name from tb
/*
id name
----------- ----------
1 A
2 A
1 B
2 B
3 B
4 B
1 C
2 C
3 C
(9 行受影响)
*/
select xh=(select count(1) from tb where name=a.name and id<a.id )+1,name from tb a order by name,xh
declare @tb table(id int,name varchar(50))
insert into @tb select 1,'A'
insert into @tb select 2,'B'
insert into @tb select 3,'C'
insert into @tb select 4,'A'
insert into @tb select 5,'B'
insert into @tb select 6,'C'
insert into @tb select 7,'B'
insert into @tb select 8,'B'
insert into @tb select 9,'C'
--2005
select id=row_number() over(partition by name order by id),name
from @tb
--2000
select id=(select count(*) from @tb where name=t.name and id<=t.id),name
from @tb t
order by name,id
SELECT ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY ID) AS ID,NAME
FROM (
SELECT ID=1, NAME='A' UNION ALL
SELECT 2, 'B' UNION ALL
SELECT 3, 'C' UNION ALL
SELECT 4, 'A' UNION ALL
SELECT 5, 'B' UNION ALL
SELECT 6, 'C' UNION ALL
SELECT 7, 'B' UNION ALL
SELECT 8, 'B' UNION ALL
SELECT 9, 'C'
) T
/*
ID NAME
-------------------- ----
1 A
2 A
1 B
2 B
3 B
4 B
1 C
2 C
3 C
*/
if object_id('tb') is not null drop table tb
go
create table tb([ID] int,[Name] varchar(10))
insert tb select 1,'A'
union all select 2,'B'
union all select 3,'C'
union all select 4,'A'
union all select 5,'B'
union all select 6,'C'
union all select 7,'B'
union all select 8,'B'
union all select 9,'C'
go
select id=(select count(1) from tb where name=t.name and id<=t.id),name from tb t order by name,id
/*
id name
----------- ----------
1 A
2 A
1 B
2 B
3 B
4 B
1 C
2 C
3 C
(9 行受影响)
*/
select 序号=(select count(1) from [Table] where Name=a.Name and id<=a.id),
Name
from [Table] a
order by 2,1