A表
------------
id  content1  content2
1   aaaaa      bbbbb   
1   ddddd      eeeee
2   ccccc      fffff
2   ggggg      hhhhh
2   wwwww      sssss将A表导入B表
---------------------------------
id   id_sort   content1   content2
1      1         aaaaa      bbbbb   
1      2         ddddd      eeeee
2      1         ccccc      fffff
2      2         ggggg      hhhhh
2      3         wwwww      sssssB表新增了字段id_sort , 每个ID都是从1开始的,并且不同的ID 都是从1开始自增
有没有办法用一句SQL达到这样的效果?

解决方案 »

  1.   


    insert B表 select id,row_number()over(partition by id order by getdate() ) from A表
      

  2.   


    insert B表 select id,
    (select count(1) from A表 where id=t.id and content1 <=t.content1 and content2<=t.content2) ,
    content1, content2 from A表 t--2005
    insert B表 select id,row_number()over(partition by id order by getdate()),content1, content2 from A表
      

  3.   


    if OBJECT_ID('tb') is not null
    drop table tb
    go
    create table tb(id int,content1 varchar(5),content2 varchar(5))
    insert into tb
    select 1, 'aaaaa', 'bbbbb' union all   
    select 1, 'ddddd', 'eeeee' union all  
    select 2, 'ccccc', 'fffff' union all  
    select 2, 'ggggg', 'hhhhh' union all  
    select 2, 'wwwww', 'sssss'select id,id_sort=ROW_NUMBER()over(partition by id order by getdate()),content1,content2
    from tbid id_sort content1 content2
    1 1 aaaaa bbbbb
    1 2 ddddd eeeee
    2 1 ccccc fffff
    2 2 ggggg hhhhh
    2 3 wwwww sssss
      

  4.   

    --sql 2000
    insert into b select id , id_sort = (select count(1) from a where id = t.id and content1 < t.content2 or (content1 = t.content2 and content1 < t.content2) ) + 1,content1 ,content2 from a t--sql 2005
    insert into b select id , id_sort = row_number() over(partition by id order by content1 , content2) ,content1 ,content2 from a t