现有一表如下:
  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
  ……   ……

解决方案 »

  1.   

    select * from tb order by name,date,id
      

  2.   

    select *,id=(select count(1) from tb where name=t.name and date<=t.date)
    from tb t
      

  3.   

    select *,row_number() over(partition by name order by date) as id from tb
      

  4.   

    顶这个吧,SQL 2005 以上可以实现
      

  5.   

    create table #t(Name varchar(10),date varchar(10))
    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 
      

  6.   

    create table #t(Name varchar(10),date varchar(10))
    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 
      

  7.   

    select Name ,Date,identity(int,1,1) into #newtable  from oldtable
    用的是临时表。
      

  8.   

    不好意思,错了,应该是:
    select name,date,
    id= row_number() over(partition by name order by identity(int,1,1) )
    from yourtable