聚合函数是用来统计每个分组的统计信息,它们要跟 group by 一起使用,用来将每个分组所有数据 聚合 成一条统计数据。

包括 max/min/count/avg/sum 等。

-- 按照部门进行分组统计的语句
select deptno,             -- 因为按照 deptno 分组,select 中只能有 deptno 字段
       count(*),           -- 每个分组多少条数据
       max(sal),           -- 每个分组工资的最大值
       min(sal),           -- 每个分组工资的最小值
       avg(sal),           -- 每个分组工资的均值
       sum(nvl(comm, 0))   -- 每个分组奖金总和,因为奖金可能为 null,所以需要使用 nvl 进行去空
  from emp
 group by deptno;          -- 分组依据


-- 可以用 having 对结果进行过滤
-- 整个 select 语句执行顺序大致是: where -> group by -> having -> order by
select deptno, count(*), max(sal), min(sal), avg(sal), sum(comm)
  from emp
 group by deptno
 having avg(sal) > 2000;

-- having 等价于嵌套的 where,即上面语句跟下面这条等效。
select * from (
  select deptno, count(*), max(sal), min(sal), avg(sal) asal, sum(comm)
    from emp
   group by deptno
 ) where asal > 2000;

相关文章:

  • 2022-12-23
  • 2021-08-05
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-19
  • 2021-10-19
  • 2021-06-04
猜你喜欢
  • 2021-08-23
  • 2021-06-24
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-11
  • 2021-12-14
相关资源
相似解决方案