---
title: "[转]SQL DISTINCT、GROUP BY"
author: "hae"
date: "2012-12-19T16:45:04Z"
tags: []
categories: ["数据库"]
slug: "sql-distinct-group-by"
draft: false
lastmod: "2012-12-19T16:45:04Z"
id: 1725687
url: "https://hae.iteye.com/blog/1725687"
---

SQL DISTINCT重复的数据统计方法 group by 重复数据的个数统计 删除重复的数据2008-09-10 16:30DISTINCT 关键字可从 SELECT 语句的结果中除去重复的行。如果没有指定 DISTINCT，那么将返回所有行，包括重复的行。   
select count(distinct t.destaddr)     from nbyd\_send t     where t.input\_time &gt; to\_date('2007-2-1','yyyy-mm-dd') and t.input\_time &lt; to\_date('2007-3-1','yyyy-mm-dd')

可以统计出一个月中的用户数量。

关于如何快速得知里面每一个号码重复的个数问题的解答:利用分组函数的SQL语句  
select t.tel,count(\*) from nbyd\_deliver t   group   by t.tel ;group by 解决重复数据的个数统计适用于各种关系型数据库,如oracle,SQL Server

查询重复的数据  
select * from (select v.xh,count(v.xh) num from sms.vehicle v group by v.xh) where num&gt;1;--169

select v.xh,count(v.xh) num from sms.vehicle v group by v.xh having count(v.xh)=2;

删除重复的数据

create table mayong as (select distinct* from sms.vehicle);

delete from sms.vehicle ;

insert into sms.vehicle select * from mayong;

在oracle中，有个隐藏了自动rowid，里面给每条记录一个唯一的rowid，我们如果想保留最新的一条记录，我们就可以利用这个字段，保留重复数据中rowid最大的一条记录就可以了。

下面是查询重复数据的一个例子：

select a.rowid,a.* from 表名 a   
where a.rowid !=   
(  
select max(b.rowid) from 表名 b   
where a.字段1 = b.字段1 and   
a.字段2 = b.字段2   
)

下面我就来讲解一下，上面括号中的语句是查询出重复数据中rowid最大的一条记录。

而外面就是查询出除了rowid最大之外的其他重复的数据了。  
由此，我们要删除重复数据，只保留最新的一条数据，就可以这样写了：  
delete from 表名 a   
where a.rowid !=   
(  
select max(b.rowid) from 表名 b   
where a.字段1 = b.字段1 and   
a.字段2 = b.字段2   
)

随便说一下，上面语句的执行效率是很低的，可以考虑建立临时表，讲需要判断重复的字段、rowid插入临时表中，然后删除的时候在进行比较。  
create table 临时表 as   
select a.字段1,a.字段2,MAX(a.ROWID) dataid from 正式表 a GROUP BY a.字段1,a.字段2;  
delete from 表名 a   
where a.rowid !=   
(  
select b.dataid from 临时表 b   
where a.字段1 = b.字段1 and   
a.字段2 = b.字段2   
);  
commit;

二、对于完全重复记录的删除

对于表中两行记录完全一样的情况，可以用下面语句获取到去掉重复数据后的记录：  
select distinct * from 表名  
可以将查询的记录放到临时表中，然后再将原来的表记录删除，最后将临时表的数据导回原来的表中。如下：  
CREATE TABLE 临时表 AS (select distinct * from 表名);  
delete from table 正式表;  
insert into 正式表 (select * from 临时表);  
drop table 临时表;