数据库中的表记录如查。
Id(自增自段),物品名称,物品规格,单价,日期1, 内存条,   256M   ,100,   2006-01-01
2, cup  ,    1.8g   ,200,   2006-01-01
3, 内存条,   256M   ,200,   2006-02-01
4, 内存条,   256M   ,150,   2006-02-11
5, cup  ,    1.8g   ,100,   2006-03-01
6, 光驱  ,    52X   ,100,   2006-03-02现在我想求一条删除语句,
想删除后的在数据库中留 下的记录为4, 内存条,   256M   ,150,   2006-02-11
5, cup  ,    1.8g   ,100,   2006-03-01
6, 光驱  ,    52X   ,100,   2006-03-02也就是说,当有两条以上的同物品名称,和同规格的物品记录时,把他们删除掉,只留下一条最近时间的。
把时间来分类,把数据库,同物品名称,和同规格的删除,只留下
最近时间的那条记录。

解决方案 »

  1.   

    delete from tablename where id not in (select top 1 id from tablename where 物品名称='' and 物品规格='' order by 日期 desc)
      

  2.   

    delete a from tbl as a
    where exists(select 1 from tbl where a.物品名称=物品名称 and
                 a.物品规格=物品规格 and a.日期<日期)
      

  3.   

    delete A 
    from 表 A
    where  exists
     (select 1 from  表 where 物品名称=A.物品名称 and 日期>A.日期)
      

  4.   

    declare @t table([id] int identity(1,1),物品名称 varchar(10),物品规格 varchar(10),单价 dec(8,2),日期 datetime)
    insert into @t select '内存条',   '256M '  ,100,   '2006-01-01'
    union all select 'cup'  ,    '1.8g'   ,200,   '2006-01-01'
    union all select '内存条',   '256M'   ,200,   '2006-02-01'
    union all select '内存条',   '256M'   ,150,   '2006-02-11'
    union all select 'cup'  ,    '1.8g'   ,100,   '2006-03-01'
    union all select '光驱 ' ,    '52X'   ,100,   '2006-03-02'
    union all select '光驱 ' ,    '52X'   ,100,   '2006-01-02'delete @t from @t a where exists(select * from @t where 物品名称=a.物品名称 and 物品规格=a.物品规格 and 日期>a.日期)select * from @t
      

  5.   

    delete a from tablename a
    where id not in (select top 1 id from tablename where 物品名称=a.物品名称 and 物品规格=a.物品规格 order by 日期 desc)
    --或者
    delete a
    from tablename a,(select 物品名称,物品规格,max(日期) as 日期 from tablename group by 物品名称,物品规格) new
    where a.物品名称=new.物品名称 and a.物品规格=new.物品规格 and a.日期<>new.日期--一个是逐行判断删除,一个是分组后联合删除。