聚合函数 db官方例子

create table bricks (

  colour varchar2(10),

  shape  varchar2(10),

  weight integer

);

insert into bricks values ( 'red', 'cube', 1 );

insert into bricks values ( 'red', 'pyramid', 2 );

insert into bricks values ( 'red', 'cuboid', 1 );

insert into bricks values ( 'blue', 'cube', 1 );

insert into bricks values ( 'blue', 'pyramid', 2 );

insert into bricks values ( 'green', 'cube', 3 );

commit;

 

count() 返回查询处理的行数,显示砖表中有多少行

 

select count ( colour ) from bricks;

 

select sum ( weight ), min ( weight ), max ( weight ),

       avg ( weight ), stddev ( weight ),

       median ( weight ), variance ( weight ),

       stats_mode ( weight )

from   bricks;

 

查找颜色列中不同值的数量。共有三种颜色(红色、绿色和蓝色)

select count ( distinct colour ) number_of_different_colours

from   bricks;

 

 

关键字 all 明确告诉函数处理每一行。您还可以使用 unique 作为 distinct 的同义词

select count ( all colour ) total_number_of_rows,

       count ( distinct colour ) number_of_different_colours,

       count ( unique colour ) number_of_unique_colours

from   bricks;

您还可以在大多数统计函数中使用 distinct,例如 sum 和 avg。

select sum ( weight ) total_weight, sum ( distinct weight ) sum_of_unique_weights,

       avg ( weight ) overall_mean, avg ( distinct weight ) mean_of_unique_weights

from   bricks;

 

分组聚合

将结果分成不同的组。您可以通过 group by 执行此操作

select colour, count (*)

from   bricks

group  by colour;

这可能会令人困惑,因此最好在选择中包含所有分组列。 

将引发异常,因为形状在选择中,但不在组中

select colour, shape, count (*)

from   bricks

group  by colour;

按多列分组。以下返回每个形状和重量的行数(脑瓜疼)

select shape, weight, count (*)

from   bricks

group  by shape, weight;

 过滤聚合

只能在 where 子句中过滤未聚合的值。如果在此处包含聚合函数,则会出现错误

select colour, count (*)

from   bricks

where  weight > 1

group  by colour;

这样就不对了

 要过滤聚合函数,请使用 having 子句。这样写是错误的

select colour, count (*)

from   bricks

where  count (*) > 1

group  by colour;

 

正确的写法

having 子句可以在 group by 之前或之后进行

select colour, count (*)

from   bricks

group  by colour

having count (*) > 1;

select colour, count (*)

from   bricks

having count (*) > 1

group  by colour;

Rollup 为其中的列生成小计 

 汇总(颜色,形状)

select colour, shape, count (*)

from   bricks

group  by rollup ( colour, shape );

 

 

select colour, shape, count (*)

from   bricks

group  by colour, rollup ( shape );

 

猜你喜欢

转载自blog.csdn.net/weixin_39568073/article/details/121220897