Oracle使用row_number over和partition实现分组排序查询最新数据

官方文档

官方地址:https://docs.oracle.com/en/database/oracle/oracle-database/21/sqlrf/ROW_NUMBER.html#GUID-D5A157F8-0F53-45BD-BF8C-AE79B1DB8C41

语法阐释

ROW_NUMBER( )
   OVER ([ query_partition_clause ] order_by_clause)

具体解释

ROW_NUMBER is an analytic function. It assigns a unique number to each row to which it is applied (either each row in the partition or each row returned by the query), in the ordered sequence of rows specified in the order_by_clause, beginning with 1. 

By nesting a subquery using ROW_NUMBER inside a query that retrieves the ROW_NUMBER values for a specified range, you can find a precise subset of rows from the results of the inner query. This use of the function lets you implement top-N, bottom-N, and inner-N reporting. For consistent results, the query must ensure a deterministic sort order.

ROM_NUMBER是一个解析函数。它给每一个所应用在order by语句描述行的有序序列的每一行(要么是分区中的每一行,要么是查询返回的每一行)分配一个唯一数字,从1开始

通过在检索指定范围查询种使用ROW_NUMBER潜逃一个子查询,可以从内部查询的结果中找到精确的行子集。

使用此函数可以实现top-N、bottom-N和inner-N报告。为了获得一致的结果,查询必须确保一个不可逆的排序顺序。

具体案例

中欧基金的的这个产品管理系统,客户提出要统计每个产品底下的资产规模日期最新的那条数据

产品是一张表,资产规模是一张表,两者用一个叫bisid的字段进行关联

我对sql不熟悉,同事用了row_number() over(partition by)这个语法,所以不得不去Oracle官网查一下

为了保密,表结构就不给了,看下实现语句吧

sql语句

select sum(fund_asset) from (
select t1.* from (select t.*,row_number() over(partition by t.bisid order by tdate desc) as rowindex 
from PMS_ASSET_SIZE t ) t1
where t1.rowindex = '1');

通俗地来讲,partition就是分区,order by就是排序,分区排序后的结果,每一行都有一个唯一标识,是数字类型

通过这个唯一标识我们可以拿到第一条,即最新的那条

论读书
睁开眼,书在面前
闭上眼,书在心里
原文地址:https://www.cnblogs.com/YC-L/p/14821498.html