Oracle 分析函数

分析函数over()

分析函数用于计算基于组的某种聚合值,它和聚合函数的不同之处是对于每个组返回多行,而聚合函数对于每个组只返回一行。
常见的分析函数如下:

  1. row_number() over(partition by ... order by ...)
  2. rank() over(partition by ... order by ...)
  3. dense_rank() over(partition by ... order by ...)
  4. sum() over(partition by ... order by ...)
  5. first_value() over(partition by ... order by ...)
  6. last_value() over(partition by ... order by ...)
  7. count() over(partition by ... order by ...):求分组后的总数。
  8. max() over(partition by ... order by ...):求分组后的最大值。
  9. min() over(partition by ... order by ...):求分组后的最小值。
  10. avg() over(partition by ... order by ...):求分组后的平均值。
  11. lag() over(partition by ... order by ...):取出前n行数据。  
  12. lead() over(partition by ... order by ...):取出后n行数据。
  13. ratio_to_report() over(partition by ... order by ...):
  14. Ratio_to_report() 括号中就是分子,over() 括号中就是分母。
  15. percent_rank() over(partition by ... order by ...):

1、分组排序

A.row_number()

  1. rank() over(partition by column1 ORDER BY column2)

column1:依据分组的列
column2:依据排序的列

  1. select prov_name, city_name, val_cnt,
  2. row_number() over(partition by prov_name ORDER BY val_cnt) AS rest
  3. from test_orer_partition_by;

image.png

B.rank()

  1. rank() over(partition by column1 ORDER BY column2)

column1:依据分组的列
column2:依据排序的列

  1. select prov_name, city_name, val_cnt,
  2. rank() over(partition by prov_name) AS rest
  3. from test_orer_partition_by;

image.png

C.dense_rank()

  1. dense_rank() over(partition by column1 ORDER BY column2)

column1:依据分组的列
column2:依据排序的列

  1. select prov_name, city_name, val_cnt,
  2. dense_rank() over(partition by prov_name ORDER BY val_cnt) AS rest
  3. from test_orer_partition_by;

image.png

2、聚合函数(sum、avg、count、max、min、first_value、last_value)

A.sum()

  1. sum() over([partition by prov_name [ORDER BY val_cnt]])

**order by**;按照排序连续累加;
**order by**,计算**partition by**后的和;
**over()**中没有**partition by**,计算所有数据总和

  1. select prov_name, city_name, val_cnt,
  2. sum(val_cnt) over(partition by prov_name ORDER BY val_cnt) AS rst
  3. from test_orer_partition_by ;

image.png

  1. select prov_name, city_name, val_cnt,
  2. sum(val_cnt) over(partition by prov_name) AS rst
  3. from test_orer_partition_by ;

image.png

  1. select prov_name, city_name, val_cnt,
  2. sum(val_cnt) over() AS rst
  3. from test_orer_partition_by ;

image.png

3、分许函数(lag、lead)

lag、lead有三个参数,第一个是表达式或字段,第二个是偏移量,第三个是为控制赋值

A.lead

  1. lead() over([partition by prov_name [ORDER BY val_cnt]])
  1. select prov_name, city_name, val_cnt,
  2. lead(val_cnt, 1) over(partition BY prov_name ORDER BY val_cnt) AS rst
  3. from test_orer_partition_by ;

image.png

  1. select prov_name, city_name, val_cnt,
  2. lead(val_cnt, 2) over(partition BY prov_name ORDER BY val_cnt) AS rst
  3. from test_orer_partition_by ;

image.png

B.lag

lag与lead用法相同,只是偏移顺序相反