龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 数据库类 > MySQL 技术 >

删除重复数据sql语句

时间:2011-03-14 23:24来源:未知 作者:admin 点击:
分享到:
删除重复数据sql语句 方法一 假设有重复的字段为name,address,要求得到这两个字段唯一的结果集 select identity(int,1,1) as autoid, * into #tmp from tablename select min(autoid) as autoid into #tmp2 from #tmp g

删除重复数据sql语句
方法一

假设有重复的字段为name,address,要求得到这两个字段唯一的结果集
select identity(int,1,1) as autoid, * into #tmp from tablename
select min(autoid) as autoid into #tmp2 from #tmp group by name,autoid
select * from #tmp where autoid in(select autoid from #tmp2)

方法二
declare @max integer,@id integer
declare cur_rows cursor local for select 主字段,count(*) from 表名 group by 主字段 having count(*) > 1
open cur_rows
fetch cur_rows into @id,@max
while @@fetch_status=0
begin
select @max = @max -1
set rowcount @max
delete from 表名 where 主字段 = @id
fetch cur_rows into @id,@max
end
close cur_rows
set rowcount 0

方法三

如果该表需要删除重复的记录(重复记录保留1条),可以按以下方法删除
select distinct * into #tmp from tablename
drop table tablename
select * into tablename from #tmp
drop table #tmp

实例

vieworder  id号      打卡机     消费类型    时间        价钱
1           a1       1号机     早餐       2006-08-03 07:09:23.000         2
2           a1       1号机     早餐       2006-08-03 07:10:13.000         2
3           a1       1号机     早餐       2006-08-03 07:10:19.000         2
4           a1       1号机     午餐       2006-08-03 12:02:10.000         5
5           a2       1号机     午餐       2006-08-03 12:11:10.000         5
6           a2       1号机     午餐       2006-08-03 12:12:10.000         5

代码

delete from 表 a
where exists(select * from 表 where  消费类型=a.消费类型 and 时间>=dateadd(minute,-2,a.时间) and 时间<a.时间)

删除之前先用select语句查看要被删除的数据
select *
from 表 a
where exists(select * from 表 where  消费类型=a.消费类型 and 时间>=dateadd(minute,-2,a.时间) and 时间<a.时间)

精彩图集

赞助商链接