distinct 和 group by 使用对比

来源:互联网 发布:linux上snmp配置 编辑:程序博客网 时间:2024/06/05 14:59

 

t3表的结构如下:
 
Select * FROM t3
id edu        age
1              20       
2              25       
3              30       
4              30       
5              25       
6              15       
7              20       
8              20       
9              20       
10            20       
11            20       
12            30       
13            30       
--------------------------------------
Select distinct edu,age
FROM t3
order by age
 
edu        age
           15       
           20       
           20       
           20        
           25       
           30       
           30      
 
小结:1、distinct edu,age 是将edu,age两个字段看成一体,只要edu,age这两个字段相同,
         就将其视为重复记录;
      2、在Select中只能用一次distinctall;
      3、在Select中用了distinct就不能用ALL;用了ALL就不能用distinct;不能同时存在;
      4、如果指定了SELECT DISTINCT,那么ORDER BY 子句中的项就必须出现在选择列表中;
---------------------------------------
select edu,age,count(*) as '人数'
--into
from t3
--where id<10
--where 分组前记录的过滤条件
group by edu,age
--having 分组后对组的过滤条件
order by age
 
edu        age         人数
           15           1
           20           1
           20           2
           20           3
           25           2
           30           2
           30           2
 
小结:1、distinct edu,age 是将edu,age两个字段看成一体,只要edu,age这两个字段相同,
         就将其视为同组;
      2SELECT子句中的列名必须为分组列或列函数;
      3where子句中的列名可以为表中任意字段;
      4having子句中的列名必须为分组列或列函数;
原创粉丝点击