请写一条sql语句:如何删除重复记录,只保留第一条记录

yanghao1 2017-10-17 07:44:00
表中有多组,组中的字段a是重复,只留组中第一条记录

例如,对于某一组有5条记录,其中字段a是重复的,只保留第一条记录,删除另外4条。
...全文
2545 14 打赏 收藏 转发到动态 举报
写回复
用AI写文章
14 条回复
切换为时间正序
请发表友善的回复…
发表回复
xuzuning 2017-10-17
  • 打赏
  • 举报
回复
对 a 列做唯一索引后复制到新表 直接删除的任何尝试都存在递归查询的问题,不是所有数据库系统都支持的
大然然 2017-10-17
  • 打赏
  • 举报
回复
引用 10 楼 From_TaiWan 的回复:
没有主键,似乎做不到,你可以给原表添加主键,代码如下:

alter table yourTable add ID bigint identity(1,1) not null
虽然没有指定是primaryKey,但对已有数据增加自增列,那就是主键 然后用2#写法,或者

delete from yourTable where ID not in(select top 1 ID from yourTable where fieldA='a')
你这个写发是错的,ID not in(select top 1 ID from yourTable where fieldA='a') 你会把那些 fieldA为 b, 为c,为d的全部删掉 正确做法是where fieldA='a' and ( ID not in(select top 1 ID from yourTable where fieldA='a') )
yanghao1 2017-10-17
  • 打赏
  • 举报
回复
我用的是Microsoft Office Access Database (.mdb)
yanghao1 2017-10-17
  • 打赏
  • 举报
回复
引用 10 楼 From_TaiWan 的回复:
没有主键,似乎做不到,你可以给原表添加主键,代码如下:

alter table yourTable add ID bigint identity(1,1) not null
虽然没有指定是primaryKey,但对已有数据增加自增列,那就是主键 然后用2#写法,或者

delete from yourTable where ID not in(select top 1 ID from yourTable where fieldA='a')
表里已经有大量数据了,并且有重复记录,这样就无法增加主键了。
yanghao1 2017-10-17
  • 打赏
  • 举报
回复
我大致是想这样取,结果不会循环组,只取到了表的第一条记录。请指正: sql = @"delete * from tab1 where a not in (select top 1 a from (select a from tab1 group by a)) ";
yanghao1 2017-10-17
  • 打赏
  • 举报
回复
引用 6 楼 duanzi_peng 的回复:
希望SQL语句中只与字段a有关,不与其它字段有关。因为在记录很多时,有的记录的其它字段是空的,只有a字段在任何一个记录中都不空。
秋的红果实 2017-10-17
  • 打赏
  • 举报
回复
没有主键,似乎做不到,你可以给原表添加主键,代码如下:

alter table yourTable add ID bigint identity(1,1) not null
虽然没有指定是primaryKey,但对已有数据增加自增列,那就是主键 然后用2#写法,或者

delete from yourTable where ID not in(select top 1 ID from yourTable where fieldA='a')
yanghao1 2017-10-17
  • 打赏
  • 举报
回复
引用 4 楼 wrd74 的回复:
第一条,以什么为排序呢。
任意排序,只要保留一条就行。
yanghao1 2017-10-17
  • 打赏
  • 举报
回复
引用 1 楼 duanzi_peng 的回复:
请提供可测试的表结构数据。
a,b,c,d字段都是字符串,不是数字 a,b,c,d 3,2,t,4 5,0,2,3 3,u,1,1 2,0,p,8 c,8,p,f 3,2,r,1 2,5,9,n 处理结果是: a,b,c,d 3,2,t,4 5,0,2,3 2,0,p,8 c,8,p,f
我要回农村z 2017-10-17
  • 打赏
  • 举报
回复
连主键这些也没有?
exception92 2017-10-17
  • 打赏
  • 举报
回复
wrd74 2017-10-17
  • 打赏
  • 举报
回复
第一条,以什么为排序呢。
大然然 2017-10-17
  • 打赏
  • 举报
回复
delete from table where name='aaa' and id > (select min( id) from table where name = 'aaa')
exception92 2017-10-17
  • 打赏
  • 举报
回复
请提供可测试的表结构数据。

110,539

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

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