数据库 --- Group by的使用心得

Group By 从字面意义上理解就是根据“By”指定的规则对数据进行分组,所谓的分组就是将一个“数据集”划分成若干个“小区域”,然后针对若干个“小区域”进行数据处理。

1. 从表中筛选出那些重复的数据 :

select * from table group by name having count(*) >1;

 

2. 写SQl语句根据名字(NAME)相同按年龄(AGE)分组得到不同年龄的人的平均工资,并写出结果:

select avg(salary) from staff group by name, age;

3. 查询A(ID,Name)表中第31至40条记录,ID作为主键可能是不是连续增长的列,完整的查询语句如下:
 
select top 10 * from A where ID >(select max(ID) from (select top 30 ID from A order by A ) T) order by A

4. 查询表A中存在ID重复三次以上的记录,完整的查询语句如下:
 
select * from(select count(ID) as count from table group by ID)T where T.count>3

 

5. 查询各个职位员工工资大于平均工资(平均工资包括所有员工)的人数和员工职位:

select job, count(*) from emp where sal > (select avg(sal) from emp) group by job;

6. 查询每个部门的最高工资:

select deptno, max(sal) maxsal from emp group by deptno order by deptno;

 

------------------------------------ 未完待续 --------------------------------------



posted @ 2018-03-13 22:05  Xbingbing  阅读(278)  评论(0编辑  收藏  举报