Oracle中group by用法


在select 语句中可以使用group by 子句将行划分成较小的组,一旦使用分组后select操作的对象变为各个分组后的数据,使用聚组函数返回的是每一个组的汇总信息。

使用having子句 限制返回的结果集。group by 子句可以将查询结果分组,并返回行的汇总信息Oracle 按照group by 子句中指定的表达式的值分组查询结果。
在带有group by 子句的查询语句中,在select 列表中指定的列要么是group by 子句中指定的列,要么包含聚组函数  select max(sal),job emp group by job;  (注意max(sal),job的job并非一定要出现,但有意义)  查询语句的select 和group by ,having 子句是聚组函数唯一出现的地方,在where 子句中不能使用聚组函数。  select deptno,sum(sal) from emp where sal>1200 group by deptno having sum(sal)>8500 order by deptno;  当在gropu by 子句中使用having 子句时,查询结果中只返回满足having条件的组。在一个sql语句中可以有where子句和having子句。having 与where 子句类似,均用于设置限定条件  where 子句的作用是在对查询结果进行分组前,将不符合where条件的行去掉,即在分组之前过滤数据,条件中不能包含聚合函数,使用where条件显示特定的行。

having 子句的作用是筛选满足条件的组,即在分组之后过滤数据,条件中经常包含聚合函数,使用having 条件显示特定的组,也可以使用多个分组标准进行分组。

使用order by排序时order by子句置于group by 之后 并且 order by 子句的排序标准不能出现在select查询之外的列。
查询每个部门的每种职位的雇员数

select deptno,job,count(*) from emp group by deptno,job

/****************************************************************

记住这就行了:

在使用group by 时,有一个规则需要遵守,即出现在select列表中的字段,如果没有在组函数中,那么必须出现在group by 子句中。(select中的字段不可以单独出现,必须出现在group语句中或者在组函数中。)
列如表内容:
id      content        idplace
1       2009-06-05      上海
1       2009-07-05      广州
2       2009-07-08      北京
3       2009-08-10      北京

要得到的结果
id      content        idplace
1       2009-06-05      上海
2       2009-07-08      北京
3       2009-08-10      北京

每个id只取一条记录,如遇到相同id的记录,筛选依据是选content字段值小的
select
  *
from
  tb t
where
  not exists(select 1 from tb where id=t.id and content<t.content)

select * from tb t where not exists(select 1 from tb where id=t.id and content<t.content)

select
  *
from
  tb t
where
  content=(select top 1 content from tb where id=t.id order by content)

select * from tb t where content=(select min(content) from tb where id=t.id )

select
  *
from
  tb t
where
  content in  (select   top 1 content  from tb where id=t.id  order by  content )
转至 http://www.cnblogs.com/wanggd/p/3512214.html

猜你喜欢

转载自401158000.iteye.com/blog/2309320