SQL删除重复数据
一、具有主键的情况
I.具有唯一性的字段id(为唯一主键)
delete 用户表
where id not in
(
select max(id) from 用户表 group by col1,col2,col3...
)
group by 子句后跟的字段就是你用来判断重复的条件,如只有col1,
那么只要col1字段内容相同即表示记录相同。
II.具有联合主键
假设col1+','+col2+','...col5 为联合主键
(找出相同记录)
select * from 用户表 where col1+','+col2+','...col5 in
(
select max(col1+','+col2+','...col5) from 用户表
group by col1,col2,col3,col4
having count(*)>1
)
group by 子句后跟的字段就是你用来判断重复的条件,
如只有col1,那么只要col1字段内容相同即表示记录相同。
或者:
(找出相同记录)
select * from 用户表 where exists (select 1 from 用户表 x where 用户表.col1 = x.col1 and
用户表.col2= x.col2 group by x.col1,x.col2 having count(*) >1)
III:判断所有的字段
select * into #aa from 用户表 group by id1,id2,....
delete 用户表
insert into 用户表 select * from #aa
二、没有主键的情况
I.用临时表实现
select identity(int,1,1) as id,* into #temp from 用户表
delete #temp
where id not in
(
select max(id) from # group by col1,col2,col3...
)
delete 用户表 ta
inset into ta(...) select ..... from #temp
II.用改变表结构(加一个唯一字段)来实现
alter 用户表 add newfield int identity(1,1)
delete 用户表
where newfield not in
(
select min(newfield) from 用户表 group by 除newfield外的所有字段
)
alter 用户表 drop column newfield
相关文档:
系统环境:Windows 7
软件环境:Visual C++ 2008 SP1 +SQL Server 2005
本次目的:编写一个航空管理系统
这是数据库课程设计的成果,虽然成绩不佳,但是作为我用VC++ 以来编写的最大程序还是传到网上,以供参考。用VC++ 做数据库设计并不容易,但也不是不可能。以下是我的程序界面,后面 ......
package cn.com.hbivt.util;
/**
* <p>Title: </p>
*
* <p>Description: </p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: </p>
*
* @author not attributable
* @version 1.0
*/
public class StringUtils {
//过滤通过页面表单提交 ......
子表查询,父表一定要加别名,否则数据会有问题,不报编译错
select * from table1 a where exist(select 1 from table2 where a.id=b.id)
存储过程结果集插入到现有表
insert into table1 exec procname args
联合已有表,紧跟在后面,对汇总很有用
select a from table1 union all select '合计'
结果集里的某 ......
在网上下了一个版本的SQL2008,一步步安装,安装过程中遇到了redist.cab 和Sql.cab错误,但基本功能还是能用,但还是不能容忍错误的存在,经一番搜索,终于找到了解决方案:
下载msxml安装,我一口气安装了msxml4.0 sp3和msxml6.0两个文件
为什么安装这个东西那?
想起来了,因为安装时报的错误是与网络有关系,而我的win ......
作者:敖士伟
一张有group by后可能很多重复行,这时用not in等基于唯一列的分布算法会存在问题。
我的解决办法是:
一张表有一个id int的主键,对其它列进行group by,分页思想是:把max(id)做group by后的唯一列,还是用not in的分布思想。
例:
select top 4 sum(int_TZ2_id) as id,dt_TZ2_date,vchar_TZ2_Pin ......