求一条简单的删除语句,这样的语句我还真不知道怎么来写,谢谢大家了。

梦回童年001 2006-04-03 04:27:44
数据库中的表记录如查。
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

也就是说,当有两条以上的同物品名称,和同规格的物品记录时,把他们删除掉,只留下一条最近时间的。
把时间来分类,把数据库,同物品名称,和同规格的删除,只留下
最近时间的那条记录。
...全文
171 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
梦回童年001 2006-04-03
  • 打赏
  • 举报
回复
强,果然都是高手。结贴。
xeqtr1982 2006-04-03
  • 打赏
  • 举报
回复
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
rivery 2006-04-03
  • 打赏
  • 举报
回复
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.日期

--一个是逐行判断删除,一个是分组后联合删除。
zlp321002 2006-04-03
  • 打赏
  • 举报
回复
delete A
from 表 A
where exists
(select 1 from 表 where 物品名称=A.物品名称 and 日期>A.日期)
WangZWang 2006-04-03
  • 打赏
  • 举报
回复
delete a from tbl as a
where exists(select 1 from tbl where a.物品名称=物品名称 and
a.物品规格=物品规格 and a.日期<日期)
jwt1982 2006-04-03
  • 打赏
  • 举报
回复
delete from tablename where id not in (select top 1 id from tablename where 物品名称='' and 物品规格='' order by 日期 desc)

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧