Sql distinct和group by的区别

distinct和Group by 区别: 
distinct只是将重复的行从结果中出去; 
group by是按指定的列分组,一般这时在select中会用到聚合函数。 
distinct是把不同的记录显示出来。 
group by是在查询时先把纪录按照类别分出来再查询。 
group by 必须在查询结果中包含一个聚集函数,而distinct不用。 

聚合函数 :
AVG 
MAX 
MIN 
SUM 
COUNT 

假定 Table 表有三列, 
id, key, value 
其中 id是主键,不能重复,key和value可能有重复记录 
 
使用distinct去重复: 
select distinct key,value 
from table 
不能显示主键。 
 
使用group by 去重复 
select id,key,value from table A, 
(select key,value, min(id) PID 
from table group by key,value 
) B 
where A.id=b.PID 
可以显示主键

猜你喜欢

转载自blog.csdn.net/hezudao25/article/details/59481894