zoukankan      html  css  js  c++  java
  • Oracle row_number() over() 分析函数--取出最新数据

    语法格式:row_number() over(partition by 分组列 order by 排序列 desc)

    一个很简单的例子

    1,先做好准备

    复制代码
    create table test1(
           id varchar(4) not null,
           name varchar(10) null,
           age varchar(10) null
    );
    
    select * from test1;
    
    insert into test1(id,name,age) values(1,'a',10);
    insert into test1(id,name,age) values(1,'a2',11);
    insert into test1(id,name,age) values(2,'b',12);
    insert into test1(id,name,age) values(2,'b2',13);
    insert into test1(id,name,age) values(3,'c',14);
    insert into test1(id,name,age) values(3,'c2',15);
    insert into test1(id,name,age) values(4,'d',16);
    insert into test1(id,name,age) values(5,'d2',17);
    复制代码

    2,开始使用之

    按照id进行分组,age进行排序,数据展示为按照相同的id分组,age从小到大排序:

    select t.id,
           t.name,
           t.age,
           row_number() over(partition by t.id order by t.age asc) rn
      from test1 t

    结果:

      id   name    age    rn

      1   a    10   1
      1   a2    11    2
      2   b    12   1
      2   b2    13   2
      3   c    14   1
      3   c2    15    2
      4   d    16   1
      5   d2   17   1

    3,进一步排序

    按照id进行分组,age进行排序,数据展示为按照相同的id分组,age从小到大排序,并取出相同id中年龄最小的一条

    select * from (select t.id,
           t.name,
           t.age,
           row_number() over(partition by t.id order by t.age asc) rn
      from test1 t) where rn < 2

    结果:

       id    name   age    rn

      1   a   10   1
      2   b   12   1
      3   c   14   1
      4   d   16   1
      5   d2   17    1

    4,总结

      工作半年的经验来看,基本上row_number() over()这个函数主要用在各种数据统计的sql中,感觉比group by好用的都,可以在一个查询中对多列数据进行分组,尤其在多表关联查询中,row_number() over()还是非常便捷的。

    整理自:https://www.cnblogs.com/moon-jiajun/p/3530035.html

  • 相关阅读:
    类的创建
    线性规划
    break、continue、pass介绍
    array numpy 模块
    hive字符串函数
    进化的Spark, 从DataFrame说起
    hive sql split 分隔符
    Spark On YARN内存分配
    浅谈Spark应用程序的性能调优
    Spark-Mllib(二)基本统计
  • 原文地址:https://www.cnblogs.com/xibuhaohao/p/11866154.html
Copyright © 2011-2022 走看看