现有一表如下:
Name Date
李四 0607
张三 0607
李四 0609
张三 0701
李四 0705
王五 0609
王五 0704
李四 0703
…… ……
现要的到如下表:
Name Date Id
李四 0607 1
李四 0609 2
李四 0705 3
李四 0703 4
王五 0609 1
王五 0704 2
张三 0607 1
张三 0701 2
…… ……
Name Date
李四 0607
张三 0607
李四 0609
张三 0701
李四 0705
王五 0609
王五 0704
李四 0703
…… ……
现要的到如下表:
Name Date Id
李四 0607 1
李四 0609 2
李四 0705 3
李四 0703 4
王五 0609 1
王五 0704 2
张三 0607 1
张三 0701 2
…… ……
from tb t
insert into #t
select '李四','0607' union all
select '张三','0607'union all
select '李四','0609'union all
select '张三','0701'union all
select '李四','0705'union all
select '王五','0609'union all
select '王五','0704'union all
select '李四','0703'--sql2000
select *,(select count(*) from #t a where a.Name=b.Name and a.date<=b.date) id from #t b
order by Name,date--sql2005
select row_number() over(partition by Name order by date) id ,Name,date from #t
insert into #t
select '李四','0607' union all
select '张三','0607'union all
select '李四','0609'union all
select '张三','0701'union all
select '李四','0705'union all
select '王五','0609'union all
select '王五','0704'union all
select '李四','0703'--sql2000
select *,(select count(*) from #t a where a.Name=b.Name and a.date<=b.date) id from #t b
order by Name,date--sql2005
select row_number() over(partition by Name order by date) id ,Name,date from #t
用的是临时表。
select name,date,
id= row_number() over(partition by name order by identity(int,1,1) )
from yourtable