请教一个关于删除重新记录的问题。

乐仪 2014-02-06 09:29:44
数据库表结构:
字段    说明
id
tyear 年
tmonth   月
companyid 企业ID
....

要保留相同companyid,同年同月的记录中,ID值最小的一条记录,删除其他重复记录。
等,急!谢谢!
...全文
114 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
LongRui888 2014-02-06
  • 打赏
  • 举报
回复
对了,如果这个id对于 不同的companyid,tyear,tmonth分组,是不重复的,那么not in是没问题的,如果有重复的id,那么not in就有为问题了。
LongRui888 2014-02-06
  • 打赏
  • 举报
回复
楼主的水平很不错的,要相信自己的实力哈,加油
LongRui888 2014-02-06
  • 打赏
  • 举报
回复
你自己写的那个not in的语句也是对的,其实思想是一样的。 写法确实也是有很多种
zlp321002 2014-02-06
  • 打赏
  • 举报
回复

delete ta from 表 ta where not exists(select 1 from 表 tb where ta.tyear=tb.tyear and  ta.tmonth= tb.tmonth
and ta.companyid=tb.companyid and ta.id<tb.id)
LongRui888 2014-02-06
  • 打赏
  • 举报
回复
如果是sql server 2000,可以试试这个:
delete 表
from
(
select companyid,tyear,tmonth,min(id) as id
from 表
group by companyid,tyear,tmonth
)t
where t.companyid=表.companyid and t.tyear =表.tyear and t.tmonth = 表.tmonth 
     and t.id < 表.id
LongRui888 2014-02-06
  • 打赏
  • 举报
回复
修改一下:
;with t
as
(
select *,
       ROW_NUMBER() over(partition by companyid,tyear,tmonth order by id) as rownum
from 表 
)
 
delete from t
where rownum > 1
LongRui888 2014-02-06
  • 打赏
  • 举报
回复
适合2005及以上版本
;with t
as
(
select *,
       ROW_NUMBER() over(order by companyid,tyear,tmonth order by id) as rownum
from 表 
)
 
delete from t
where rownum > 1

22,297

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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