SQL distinct 和group by

聚合函数
AVG
MAX
MIN
SUM
COUNT


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

假定 Table 表有三列,
id, key, value
其中 id是主键,不能重复,key和value可能有重复记录


使用distinct去重复:
select distinct key,value
from table
不能显示主键。


使用group by 去重复
select count(*) from table A,
(select key,value, min(id) PID
from table group by key,value
) B
where A.id=b.PID

猜你喜欢

转载自lemon-1227.iteye.com/blog/1851325