根据多个(非一个)字段删除重复记录,数据如下

FSU 2013-01-24 09:38:30
ID Dep UserID UserName sDate
6DD260E6-3A6B-42ED-8630-197802AAB6B3 财务部 _f_00017 刘小宝 2012-08-27 00:00:00.000
FB61B5B3-8E8A-4852-87AC-AFBA081FD858 财务部 _f_00017 刘小宝 2012-08-27 00:00:00.000
D839A562-0198-418E-B683-239C49871E90 财务部 _f_00016 王明 2012-08-27 00:00:00.000
7B1DCCBC-B31E-4858-8DFF-763F80DE0198 财务部 _f_00016 王明 2012-08-27 00:00:00.000
6821CCE4-C7A6-4971-8FA6-AA31CD0D327A 产供部 _f_00027 张彬彬 2012-08-27 00:00:00.000
256B1839-A6B9-4756-9B8A-0267C3F7688E 产供部 _f_00027 张彬彬 2012-08-27 00:00:00.000

要求:根据 UserID,sDate 删除重复记录,重复记录只保留一条
期望结果如下:
ID Dep UserID UserName sDate
6DD260E6-3A6B-42ED-8630-197802AAB6B3 财务部 _f_00017 刘小宝 2012-08-27 00:00:00.000
D839A562-0198-418E-B683-239C49871E90 财务部 _f_00016 王明 2012-08-27 00:00:00.000
6821CCE4-C7A6-4971-8FA6-AA31CD0D327A 产供部 _f_00027 张彬彬 2012-08-27 00:00:00.000
...全文
112 5 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
中国风 2013-01-24
  • 打赏
  • 举报
回复
delete a
from (select * ,row_number()over( partition by UserID,sDate order by ID) as Row from 表名) as a
where Row>1
SQL05以上版本可以直接用
叶子 2013-01-24
  • 打赏
  • 举报
回复
用到uniqueidentifier 列的时候转换一下 转成nvarchar 例如
delete tb where not exists
(select 1 from tb as a where a.userid=tb.userid and a.sDate=tb.sDate
group by a.userid,a.sDate having min(cast(a.id as varchar(40)))=cast(tb.id as varchar(40)))
FSU 2013-01-24
  • 打赏
  • 举报
回复
delete tb where not exists (select 1 from tb as a where a.userid=tb.userid and a.sDate=tb.sDate group by a.userid,a.sDate having min(a.id)=tb.id) =========== 我这个数据库是SQL SERVER 2000,ID字段是数据类型是:uniqueidentifier ,所以将出现以下错误: minimum aggregate 运算不能以 uniqueidentifier 数据类型作为参数。
shoppo0505 2013-01-24
  • 打赏
  • 举报
回复
with tb as ( SELECT tbtmp.*,row=ROW_NUMBER()OVER(Partition by UserID, sDate order by ID) FROM yourtable ) delete from yourtable where ID in ( SELECT ID from tb where row <>1 )
szm341 2013-01-24
  • 打赏
  • 举报
回复
delete tb where not exists (select 1 from tb as a where a.userid=tb.userid and a.sDate=tb.sDate group by a.userid,a.sDate having min(a.id)=tb.id)

27,581

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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