开窗函数

开窗函数介绍

开窗函数用于为行定义一个窗口(这里的窗口是指运算将要操作的行的集合),它对一组值进行操作,不需要使用GROUP BY子句对数据进行分组,能够在同一行中同时返回基础行的列和聚合列。

创建表

create table MYTAB
(
  cid   VARCHAR2(50),
  name  VARCHAR2(50),
  score VARCHAR2(50)
)
tablespace USERS
  pctfree 10
  initrans 1
  maxtrans 255
  storage
  (
    initial 64K
    next 1M
    minextents 1
    maxextents unlimited
  );

导入inset语句

prompt Importing table mytab...
set feedback off
set define off
insert into mytab (CID, NAME, SCORE)
values ('1', 'LS', '70');

insert into mytab (CID, NAME, SCORE)
values ('1', 'ZS', '60');

insert into mytab (CID, NAME, SCORE)
values ('1', 'WW', '80');

insert into mytab (CID, NAME, SCORE)
values ('2', 'BB', '90');

insert into mytab (CID, NAME, SCORE)
values ('2', 'AA', '80');

insert into mytab (CID, NAME, SCORE)
values ('2', 'ZL', '90');

insert into mytab (CID, NAME, SCORE)
values ('1', 'qq', '70');

prompt Done.

函数介绍

select cid,NAME,SCORE,
--窗口函数排序

        /*依据每个班上的考试人数进行排名*/
        row_number() over(partition by cid order by score)rn,

        rank() over(partition by cid order by score)rk,

        dense_rank() over(partition by cid order by score)drk,

-- 窗口函数聚合

        /*计算班上每个同学都知道班上总分多少分*/
        sum(score) over(partition by cid) as sum1,

        /*计算每个学生包括自己,及比自己低的总分是多少*/
        sum(score) over(partition by cid order by score) as sum2,
        --等价于
        sum(score) over(partition by cid order by score range between unbounded preceding and current row) as sum3,
        sum(score) over(partition by cid order by score rows between unbounded preceding and current row)as sum4, ----但不等价于rows(自行体会)

        /*计算每个学生包括自己,及比自己高的总分是多少*/
        sum(score) over(partition by cid order by score desc) as sum5,
        --等价于
        sum(score) over(partition by cid order by score range between current row and unbounded following)as sum6,
        sum(score) over(partition by cid order by score desc range between unbounded preceding and current row)as sum7,

--向前向后取数
        /*查询比自己低的考试分数是多少*/
        lag(score) over(partition by cid order by score)lag1,
        /*查询比自己低的考试分数是多少,为空的拿0代替*/
        lag(score,1,0) over(partition by cid order by score)lag2,
        
        /*查询比自己高的考试分数是多少*/
        lead(score) over(partition by cid order by score)lead1,

--first_value,last_value
        
        /*查询每个同学让全班同学都知道班上最低分数多少分*/
        first_value(score) over(partition by cid order by score) first1,
        
        /*查询每个同学让全班同学都知道班上最低分数多少分*/
        last_value(score) over(partition by cid order by score) last1,
        last_value(score) over(partition by cid order by score rows between unbounded preceding and unbounded following) last2
                  
from mytab
image.png

你可能感兴趣的:(开窗函数)