首页 > 其他分享 >FIRST and LAST Analytic Functions

FIRST and LAST Analytic Functions

时间:2025-01-21 19:57:29浏览次数:3  
标签:Functions LAST sal 2850 30 Analytic emp 20 3000

This article gives an overview of the FIRST and LAST analytic functions. If you are new to analytic functions you should probably read this introduction to analytic functions first.

Most of the time I find myself using FIRST_VALUE and LAST_VALUE Analytic Functions in preference to FIRST and LAST. Pick which feels best for your use case.

Content

Setup

FIRST Analytic Function

LAST Analytic Function


Related articles.

Setup

The examples in this article require the following table.

--drop table emp purge;

create table emp (
  empno    number(4) constraint pk_emp primary key,
  ename    varchar2(10),
  job      varchar2(9),
  mgr      number(4),
  hiredate date,
  sal      number(7,2),
  comm     number(7,2),
  deptno   number(2)
);

insert into emp values (7369,'SMITH','CLERK',7902,to_date('17-12-1980','dd-mm-yyyy'),800,null,20);
insert into emp values (7499,'ALLEN','SALESMAN',7698,to_date('20-2-1981','dd-mm-yyyy'),1600,300,30);
insert into emp values (7521,'WARD','SALESMAN',7698,to_date('22-2-1981','dd-mm-yyyy'),1250,500,30);
insert into emp values (7566,'JONES','MANAGER',7839,to_date('2-4-1981','dd-mm-yyyy'),2975,null,20);
insert into emp values (7654,'MARTIN','SALESMAN',7698,to_date('28-9-1981','dd-mm-yyyy'),1250,1400,30);
insert into emp values (7698,'BLAKE','MANAGER',7839,to_date('1-5-1981','dd-mm-yyyy'),2850,null,30);
insert into emp values (7782,'CLARK','MANAGER',7839,to_date('9-6-1981','dd-mm-yyyy'),2450,null,10);
insert into emp values (7788,'SCOTT','ANALYST',7566,to_date('13-JUL-87','dd-mm-rr')-85,3000,null,20);
insert into emp values (7839,'KING','PRESIDENT',null,to_date('17-11-1981','dd-mm-yyyy'),5000,null,10);
insert into emp values (7844,'TURNER','SALESMAN',7698,to_date('8-9-1981','dd-mm-yyyy'),1500,0,30);
insert into emp values (7876,'ADAMS','CLERK',7788,to_date('13-JUL-87', 'dd-mm-rr')-51,1100,null,20);
insert into emp values (7900,'JAMES','CLERK',7698,to_date('3-12-1981','dd-mm-yyyy'),950,null,30);
insert into emp values (7902,'FORD','ANALYST',7566,to_date('3-12-1981','dd-mm-yyyy'),3000,null,20);
insert into emp values (7934,'MILLER','CLERK',7782,to_date('23-1-1982','dd-mm-yyyy'),1300,null,10);
commit;

FIRST Analytic Function

The FIRST analytic function can be used to return the first value from an ordered sequence. Say we want to display the salary of each employee, along with the lowest salary within their department we may use something like.

select empno,
       deptno,
       sal,
       min(sal) keep (dense_rank first order by sal) over (partition by deptno) as lowest
from   emp
order by deptno, sal;

     EMPNO     DEPTNO        SAL     LOWEST
---------- ---------- ---------- ----------
      7934         10       1300       1300
      7782         10       2450       1300
      7839         10       5000       1300
      7369         20        800        800
      7876         20       1100        800
      7566         20       2975        800
      7788         20       3000        800
      7902         20       3000        800
      7900         30        950        950
      7654         30       1250        950
      7521         30       1250        950
      7844         30       1500        950
      7499         30       1600        950
      7698         30       2850        950

SQL>

The MIN function is almost irrelevant here as it's FIRST and KEEP that are picking the row whose value will be used. We can demonstrate this by using MAX for the low value.

select empno,
       deptno,
       sal,
       max(sal) keep (dense_rank first order by sal) over (partition by deptno) as lowest
from   emp
order by deptno, sal;

     EMPNO     DEPTNO        SAL     LOWEST
---------- ---------- ---------- ----------
      7934         10       1300       1300
      7782         10       2450       1300
      7839         10       5000       1300
      7369         20        800        800
      7876         20       1100        800
      7566         20       2975        800
      7788         20       3000        800
      7902         20       3000        800
      7900         30        950        950
      7654         30       1250        950
      7521         30       1250        950
      7844         30       1500        950
      7499         30       1600        950
      7698         30       2850        950

SQL>

We get the same result.

We could also achieve the same result using FIRST_VALUE or MIN as basic analytic functions. In practice I don't use FIRST very often.

LAST Analytic Function

The LAST analytic function can be used to return the last value from an ordered sequence. Say we want to display the salary of each employee, along with the highest within their department we may use something like.

select empno,
       deptno,
       sal,
       max(sal) keep (dense_rank last order by sal) over (partition by deptno) as highest
from   emp
order by deptno, sal;

     EMPNO     DEPTNO        SAL    HIGHEST
---------- ---------- ---------- ----------
      7934         10       1300       5000
      7782         10       2450       5000
      7839         10       5000       5000
      7369         20        800       3000
      7876         20       1100       3000
      7566         20       2975       3000
      7788         20       3000       3000
      7902         20       3000       3000
      7900         30        950       2850
      7654         30       1250       2850
      7521         30       1250       2850
      7844         30       1500       2850
      7499         30       1600       2850
      7698         30       2850       2850

SQL>

The MAX function is almost irrelevant here as it's LAST and KEEP that are picking the row whose value will be used. We can demonstrate this by using MIN for the high value.

select empno,
       deptno,
       sal,
       min(sal) keep (dense_rank last order by sal) over (partition by deptno) as highest
from   emp
order by deptno, sal;

     EMPNO     DEPTNO        SAL    HIGHEST
---------- ---------- ---------- ----------
      7934         10       1300       5000
      7782         10       2450       5000
      7839         10       5000       5000
      7369         20        800       3000
      7876         20       1100       3000
      7566         20       2975       3000
      7788         20       3000       3000
      7902         20       3000       3000
      7900         30        950       2850
      7654         30       1250       2850
      7521         30       1250       2850
      7844         30       1500       2850
      7499         30       1600       2850
      7698         30       2850       2850

SQL>

We get the same result.

We could also achieve the same result using LAST_VALUE or MAX as basic analytic functions. In practice I don't use LAST very often.

The "*" indicates the function supports the full analytic syntax, including the windowing clause.

AVG *BIT_AND_AGG *BIT_OR_AGG *BIT_XOR_AGG *CHECKSUM *
CLUSTER_DETAILSCLUSTER_DISTANCECLUSTER_IDCLUSTER_SETCORR *
COUNT *COVAR_POP *COVAR_SAMP *CUME_DISTDENSE_RANK
FEATURE_DETAILSFEATURE_IDFEATURE_SETFEATURE_VALUEFIRST
FIRST_VALUE *KURTOSIS_POP *KURTOSIS_SAMP *LAGLAST
LAST_VALUE *LEADLISTAGGMATCH_RECOGNIZEMAX *
MEDIANMIN *NTH_VALUE *NTILEPERCENT_RANK
PERCENTILE_CONTPERCENTILE_DISCPREDICTIONPREDICTION_COSTPREDICTION
PREDICTION_COSTPREDICTION_DETAILSPREDICTION_PROBABILITYPREDICTION_SETRANK
RATIO_TO_REPORTREGR_ (Linear Regression) Functions *ROW_NUMBERSKEWNESS_POP *SKEWNESS_SAMP *
STDDEV *STDDEV_POP *STDDEV_SAMP *SUM *VAR_POP *
VAR_SAMP *VARIANCE *String AggregationTop-N Queries

For more information see:

Hope this helps. Regards Tim...


我阅读了这篇文章,这篇文章呢,作者自己也说Most of the time I find myself using FIRST_VALUE and LAST_VALUE Analytic Functions in preference to FIRST and LAST. Pick which feels best for your use case.

但是,好处有以下:

  1.  写法固定,避免了讨厌的order by,如果某个人不小心写了order by之后,发现结果为什么不对,那是因为window clause的default action是range between unbouned preceding and current row,这样只扫描了当前行及其之前的所有行,但是经我测试下来,发现如果你在query partition clause之后写order by,会报错:ORA-30487: ORDER BY not allowed here。code如下
    select empno,
           deptno,
           sal,
           min(sal) keep (dense_rank first order by sal) over (partition by deptno order by sal) as lowest
    from   emp
    order by deptno, sal;
  2. dense_rank能不能改?答案是不能,改了会报错:ORA-02000: missing DENSE_RANK keyword。
  3. 文章中用到的aggregate function - min or max 能不能修改?答案是可以的,因为last和first已然指定,那么用任意一个function都是不搭嘎的。

标签:Functions,LAST,sal,2850,30,Analytic,emp,20,3000
From: https://blog.csdn.net/weixin_44875522/article/details/145289305

相关文章

  • ROLLUP, CUBE, GROUPING Functions and GROUPING SETS
    ORACLE-BASE-ROLLUP,CUBE,GROUPINGFunctionsandGROUPINGSETS看不懂的可以来问-------------------------------------------------------------------------------------------------------------------------------完了,我也看不懂了思考一下几个SQL的resultsets......
  • elasticsearch 数据同步
    数据同步elasticsearch中的酒店数据来自于mysql数据库,因此mysql数据发生改变时,elasticsearch也必须跟着改变,这个就是elasticsearch与mysql之间的数据同步。异步通知流程如下:hotel-admin对mysql数据库数据完成增、删、改后,发送MQ消息hotel-demo监听MQ,接收到消息后完成elasti......
  • MySQL不香吗,为啥还要Elasticsearch?
    一、先说说MySQL有啥优点MySQL这玩意,咱们都熟。行存储的代表,关系型数据库的中流砥柱。它有啥好处?老铁,太多了:数据一致性:事务支持那是杠杠的,ACID四大天王保护你数据不丢失。结构化查询:SQL语句一出,啥复杂查询都能搞定,分组、排序、子查询,随便玩。成熟稳健:发展几十年,社区大,文档多,踩......
  • ElasticSearch 学习课程入门(一)
    ​引子前文已经介绍了windows下如何安装ES,接下来的文章我会边学习边记录。OK,那就让我们开始吧。一、ES基础操作1、预备知识(1)RESTfulREST指的是一组架构约束条件和原则。满足这些约束条件和原则的应用程序或设计就是RESTful。Web应用程序最重要的REST原则是,客户端和服务......
  • 太香了!一款轻量级的 Elasticsearch 可视化管理工具!
    大家好,我是Java陈序员。今天,给大家介绍一款轻量级的Elasticsearch可视化管理工具,可替代Kibana!关注微信公众号:【Java陈序员】,获取开源项目分享、AI副业分享、超200本经典计算机电子书籍等。项目介绍Elasticvue——一个免费且开源的Elasticsearch在线可视化客户端,用于......
  • ElasticSearch Python 使用
    目录依赖下载连接elasticsearch配置忽略响应状态码示例ElasticsearchforPython之操作结果过滤ElasticSearch(es对象)Indices(es.indices)Cluster(集群相关)Node(节点相关)Cat(一种查询方式)Snapshot(快照相关)Task(任务相关)依赖下载pipinstallelasticsearch#豆瓣源pipinstall-ihtt......
  • ElasticSearch Java 使用
    目录创建工程,导入坐标创建索引index创建映射mapping建立文档document建立文档(通过XContentBuilder)建立文档(使用Jackson转换实体)1)添加jackson坐标2)创建Article实体3)代码实现查询文档操作关键词查询字符串查询使用文档ID查询文档查询文档分页操作批量插入数据分页查询查询......
  • 【详解】ElasticSearchJava操作ES实例
    目录ElasticSearchJava操作ES实例简介环境准备1.安装Elasticsearch2.添加依赖连接Elasticsearch1.创建客户端2.关闭客户端基本操作1.创建索引2.插入数据3.查询数据环境准备示例代码代码说明运行代码1.添加依赖2.创建客户端3.索引文档4.查询......
  • ElasticSearch Query DSL(查询领域特定语言)
    目录常用DSL关键字查询上下文相关度评分:_score源数据:_source数据源过滤器query和filter上下文相关性评分(relevancescores)query的上下文filter的上下文关于query和filter上下文的例子全文查询(fulltextquery)intervals查询请求示例intervals的顶级参数match(匹......
  • Elasticsearch 笔记
    目录ES相关概念概述核心概念1)索引index2)类型type3)字段Filed4)映射mapping5)文档document6)集群cluster7)节点node8)分片和复制shards&replicas9)接近实时NRTElasticSearch字段的类型字段类型映射参数stringindex分析store存储Numericindex分析store存储dateindex分......