sql多字段去重
‘壹’ sql查询去掉重复记录
1、打开要去掉重复数据的数据库,这里新建一张含有重复数据的user表做示例,如下图所示:
‘贰’ 关于SQL去重的几种方法
1. distinct
select distinct 列名 from 表名
2. row_number
select *, row_number() over (partition by 想去重的列名 order by 列名) as row_num
from 表名
where row_num = 1
3.group by
select 列名 from 表名 group by 列名
重复量多时,GROUP BY总的处理效率比DISTINCT高,重复量低时,DISTINCT就比GROUP BY快一点了,而如果随着整体数据量的增加,效果会越来越明显。
‘叁’ SQL如何去重
1、首先创建一个临时表,用于演示sqlserver语法中的去重关键字distinct的使用。本文以sqlserver数据库为例演示,
IF OBJECT_ID('tempdb..#tmp1') IS NOT NULL DROP TABLE #tmp1;
CREATE TABLE #tmp1(
Col1 varchar(50),
Col2 int
);
‘肆’ SQL查询中如何剔除重复
1,存在两条完全相同的纪录
这是最简单的一种情况,用关键字distinct就可以去掉
example: select distinct * from table(表名) where (条件)
2,存在部分字段相同的纪录(有主键id即唯一键)
如果是这种情况的话用distinct是过滤不了的,这就要用到主键id的唯一性特点及group by分组
example:
select * from table where id in (select max(id) from table group by [去除重复的字段名列表,....])
3,没有唯一键ID
example:
select identity(int1,1) as id,* into newtable(临时表) from table
select * from newtable where id in (select max(id) from newtable group by [去除重复的字段名列表,....])
drop table newtable
(4)sql多字段去重扩展阅读
1、查找表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断
select * from people
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
2、删除表中多余的重复记录,重复记录是根据单个字段(peopleId)来判断,只留有rowid最小的记录
delete from people
where peopleId in (select peopleId from people group by peopleId having count(peopleId) > 1)
and rowid not in (select min(rowid) from people group by peopleId having count(peopleId )>1)
3、查找表中多余的重复记录(多个字段)
select * from vitae a
where (a.peopleId,a.seq) in (select peopleId,seq from vitae group by peopleId,seq having count(*) > 1)
‘伍’ sql语句去重
sql语句通过DISTINCT关键字去重, 用于返回唯一不同的值。DISTINCT关键字需要搭配SELECT 语句使用,语法为SELECT DISTINCT 列名称 FROM 表名称。如果指定了 SELECT DISTINCT,那么 ORDER BY 子句中的项就必须出现在选择列表中,否则会出现错误。
(5)sql多字段去重扩展阅读:
distinct这个关键字用来过滤掉多余的重复记录只保留一条,但往往只用它来返回不重复记录的条数,而不是用它来返回不重记录的所有值。其原因是distinct只有用二重循环查询来解决,而这样对于一个数据量非常大的站来说,无疑是会直接影响到效率的。
distinct必须放在开头,distinct语句中select显示的字段只能是distinct指定的字段,其他字段是不可能出现的。