看下表,当字段一有重复值时,比较字段二,当字段二有重复值时,比较字段三,选出唯一的。这种多重重复的SQL查询语句如何写?谢谢字段一,字段二,字段三
A,a,1
A,a,1
A,b,2
A,c,1
A,a,2
A,a,3
A,b,1
A,c,1
A,c,2
B,c,1
B,a,2
B,b,1
C,c,1
D,a,1
查询结果:字段一,字段二,字段三A,a,1
A,b,2
A,c,1
A,a,2
A,a,3
A,b,1
A,c,2
B,c,1
B,a,2
B,b,1
C,c,1
D,a,1

解决方案 »

  1.   

    本帖最后由 josy 于 2012-11-01 17:49:06 编辑
      

  2.   

    ;with f as
    (
    select id=row_number()over(order by getdate()),* from tb
    )select
     * 
    from
     f t 
    where 
    not exists(select 1 from tb where 字段1=t.字段1 and (字段2<t.字段2 or (字段2=t.字段2 and 字段3<t.字段3) or (字段2=t.字段2 and 字段3=t.字段3 and id<t.id)
      

  3.   

    ;with f as
    (
    select id=row_number()over(order by getdate()),* from tb
    )select
      *  
    from
      f t  
    where  
    not exists(select 1 from tb where 字段1=t.字段1 and (字段2<t.字段2) or (字段2=t.字段2 and 字段3<t.字段3) or (字段2=t.字段2 and 字段3=t.字段3 and id<t.id))
      

  4.   


    if(object_id('a')is not null) drop table a
    go
    create table a
    (
    a varchar(1),
    b varchar(1),
    c int
    )
    go
    insert into a
    select 'A','a',1 union all
    select 'A','a',1 union all
    select 'A','b',2 union all
    select 'A','c',1 union all
    select 'A','a',2 union all
    select 'A','a',3 union all
    select 'A','b',1 union all
    select 'A','c',1 union all
    select 'A','c',2 union all
    select 'B','c',1 union all
    select 'B','a',2 union all
    select 'B','b',1 union all
    select 'C','c',1 union all
    select 'D','a',1select a,b,c from a group by a,b,c order by a,c,b
    /*
    a    b    c
    ---- ---- -----------
    A    a    1
    A    b    1
    A    c    1
    A    a    2
    A    b    2
    A    c    2
    A    a    3
    B    b    1
    B    c    1
    B    a    2
    C    c    1
    D    a    1(12 行受影响)
    */
      

  5.   

    高手如云啊,我是楼主,谢谢各位了。稍后结贴发分。追问下:假如原表里已经有30万条记录,现在要做的动作是1、对原表数据进行上述的重复排除,2、批量插入1万条数据,要如何写高效的SQL语句?再次感谢。
      

  6.   


    ;with T as(
    select distinct 字段一,字段二,字段三 from tb
    )
    insert into 待插入数据的表名(字段一,字段二,字段三)
    select * from T
      

  7.   

    高手如云啊,我是楼主,谢谢各位了。稍后结贴发分。追问下:假如原表里已经有30万条记录,现在要做的动作是1、对原表数据进行上述的重复排除(有6个字段,前3个字段组合唯一),2、批量插入1万条数据,确保新插入的数据也和原来的数据不重复(有6个字段,前3个字段组合唯一)要如何写高效的SQL语句?再次感谢。
      

  8.   

    我建议不要使用distinct,,这会造成很大的开销可以试试别的方式去掉重复数据  比如说F妞妞的方法如果需要不重复  那你插入之前最好是检测一下  写个存储过程  吧批量数据放入到一个临时表  再去跟原表比较  如果有重复的就不插入  没有在插入