pid      bandId
------------------------------
1816 1532
1817 1532
1818 1533
1819 1533
1829 1543
1830 1543
1831 1544
1832 1544
1991 11779
207 11779使用sql语句删除'bandId'重复数据中 pid较大的数据.
1991 11779
207 11779
如上数据中,删除pid为1991的数据.

解决方案 »

  1.   

    if not object_id('tb') is null
    drop table tb
    Go
    Create table tb([pid] int,[bandId] int)
    Insert tb
    select 1816,1532 union all
    select 1817,1532 union all
    select 1818,1533 union all
    select 1819,1533 union all
    select 1829,1543 union all
    select 1830,1543 union all
    select 1831,1544 union all
    select 1832,1544 union all
    select 1991,11779 union all
    select 207,11779
    Go
    delete t
    from tb t
    where exists(select 1 from tb where [bandId]=t.[bandId] and [pid]<t.pid)
    Select * from tb
    /*
    pid         bandId
    ----------- -----------
    1816        1532
    1818        1533
    1829        1543
    1831        1544
    207         11779(5 row(s) affected)
    */
      

  2.   

    DELETE FROM TB A WHERE EXISTS(SELECT 1 FROM TB B WHERE A.pid>B.pid AND A.bandId
    =B.bandId)