為了性能考慮,在閱讀之前提醒大家,如果有子查詢,子查詢查詢到的數據最好不要超過總數據量的30%。
查詢有重復數據的記錄
select * from F group by a,b,c,d having count(*)>1
select distinct * into #Tmp from tableName
drop table tableName
select * into tableName from #Tmp
drop table #Tmp
SQL刪除重復數據方法
例如:
id name value
1 a pp
2 a pp
3 b iii
4 b pp
5 b pp
6 c pp
7 c pp
8 c iii
id是主鍵
要求得到這樣的結果
id name value
1 a pp
3 b iii
4 b pp
6 c pp
8 c iii
方法1
where [id] not in ( max([id]) from group by (name + value))
方法2
a from 表 a left join( id=min(id) from 表 group by name,value )b on a.id=b.id where b.id is null
查詢及刪除重復記錄的SQL語句 查詢及刪除重復記錄的SQL語句
1、查找表中多余的重復記錄,重復記錄是根據單個字段()來判斷
* from where in ( from group by count() > 1)
2、刪除表中多余的重復記錄,重復記錄是根據單個字段()來判斷,只留有rowid最小的記錄
from where in ( from group by count() > 1) and rowid not in ( min(rowid) from group by count( )>1)
3、查找表中多余的重復記錄(多個字段)
* from vitae a where (a.,a.seq) in ( ,seq from vitae group by ,seq count(*) > 1)
4、刪除表中多余的重復記錄(多個字段)兩種刪除表內數據的sql,只留有rowid最小的記錄
from vitae a where (a.,a.seq) in ( ,seq from vitae group by ,seq count(*) > 1) and rowid not in ( min(rowid) from vitae group by ,seq count(*)>1)
5、查找表中多余的重復記錄(多個字段),不包含rowid最小的記錄
* from vitae a where (a.,a.seq) in ( ,seq from vitae group by ,seq count(*) > 1) and rowid not in ( min(rowid) from vitae group by ,seq count(*)>1)
(二)
比方說 在A表中存在一個字段“name”,而且不同記錄之間的“name”值有可能會相同兩種刪除表內數據的sql, 現在就是需要查詢出在該表中的各記錄之間,“name”值存在重復的項;
Name,Count(*) From A Group By Name Count(*) > 1 如果還查性別也相同大則如下: Name,sex,Count(*) From A Group By Name,sex Count(*) > 1
(三)
方法一
@max ,@id local for 主字段,count(*) from 表名 group by 主字段 count(*) >; 1 open fetch into @id,@max while @@=0 begin @max = @max -1 set @max from 表名 where 主字段 = @id fetch into @id,@max end close set 0
方法二
"重復記錄"有兩個意義上的重復記錄,一是完全重復的記錄,也即所有字段均重復的記錄,二是部分關鍵字段重復的記錄,比如Name字段重復,而其他字段不一定重復或都重復可以忽略。
1、對于第一種重復,比較容易解決,使用 * from 就可以得到無重復記錄的結果集。 如果該表需要刪除重復的記錄(重復記錄保留1條),可以按以下方法刪除
* into #Tmp from drop table * into from #Tmp drop table #Tmp
發生這種重復的原因是表設計不周產生的,增加唯一索引列即可解決。
2、這類重復問題通常要求保留重復記錄中的第一條記錄,操作方法如下 假設有重復的字段為Name,,要求得到這兩個字段唯一的結果集
(int,1,1) as , * into #Tmp from min() as into #Tmp2 from #Tmp group by Name, * from #Tmp where in( from #tmp2)
最后一個即得到了Name,不重復的結果集(但多了一個字段,實際寫時可以寫在子句中省去此列)
(四) 查詢重復
* from where id in ( id from group by id count(id) > 1 )
去重:
-- //////////////////////////////////實現1
DELETE
FROM
tableName
WHERE
id NOT IN (
SELECT
*
FROM
(
SELECT
min(t3.id)
FROM
tableName t3
GROUP BY
column1(即去重的字段)
) t2
)
-- //////////////////////////////////實現2
DELETE
FROM
tableName t1
WHERE
t1.id NOT IN (
SELECT
*
FROM
(
SELECT DISTINCT
id
FROM
tableName t3
) t2
)