设为首页 加入收藏

TOP

删除重复数据sql语句
2011-06-12 21:45:46 来源: 作者: 【 】 浏览:97次 评论:0

删除重复数据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.时间)

您看到此篇文章时的感受是:
Tags: 责任编辑:administrator
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到QQ空间
分享到: 
上一篇引起 MySQL server has gone away.. 下一篇mysql concat() 字符连接函数

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

相关栏目

最新文章

图片主题

热门文章

推荐文章

相关文章

广告位