The method of taking other column data after Oracle aggregation function - window function

Oracle's aggregation function is executed after the group by grouping, so the grouping in the aggregation function, such as partition by, is executed in the result set after the entire select is completed, in other words group by will not affect the partition by in the aggregation function Grouping; the aggregation function can use the group by group as the basis for aggregation, or define the group by itself through partition by, and then perform the aggregation operation

The difference between window function and aggregate function

Aggregation functions usually only return the aggregated results and the key fields of the aggregation. If you need to return the values ​​of columns other than the aggregated columns, you need to use the window function. Unlike the aggregate function, the window function will merge the aggregated results into the original result set


Usage scenario: For example, there are columns KEY, VALUE, and DATE in a table Table1

KEY (Student) VALUE (grade) DATE (date)
Zhang San 89 2021/01/02
Zhang San 72 2021/11/12
Li Si 63 2021/10/12
Li Si 91 2021/11/14

A certain business needs to summarize according to the students, remove duplicates, and only get the results of the latest date
Group BY statement:

SELECT A.KEY,A.VALUE,A.DATE FROM TABLE1 A
 (SELECT MAX(DATE),KEY FROM TABLE1 GROUP BY KEY) B
WHERE A.KEY = B.KEY AND  A.DATE = B.DATE

GROUP BY result:

KEY (Student) VALUE (grade) DATE (date)
Zhang San 72 2021/11/12
Li Si 91 2021/11/14

Use the window function FIRST_VALUE to get the first item sorted by ORDER after aggregation by KEY
FIRST_VALUE(A.VALUE)OVER( PARTITION BY A.KEY ORDER BY A.DATE DESC)

SELECT KEY,FIRST_VALUE(A.VALUE)OVER(
PARTITION BY A.KEY ORDER BY A.DATE DESC) AS NVALUE,VALUE,DATE FROM TABLE1 A

Window function result

KEY (Student) VALUE (grade) NVALUE (latest grade) DATE (date)
Zhang San 89 72 2021/01/02
Zhang San 72 72 2021/11/12
Li Si 63 91 2021/10/12
Li Si 91 91 2021/11/14

Then remove duplicates, use ROW_NUMBER() to record the same type of data, and then filter out the latest items
ROW_NUMBER() OVER( PARTITION BY A.KEY ORDER BY A.DATE DESC)

SELECT * FROM (SELECT KEY,FIRST_VALUE(A.VALUE)OVER(
PARTITION BY A.KEY ORDER BY A.DATE DESC) AS NVALUE,ROW_NUMBER() OVER(
PARTITION BY A.KEY ORDER BY A.DATE DESC) AS 
RWORDER ,VALUE,DATE FROM TABLE1 A) WHERE RWORDER =1

Final Results

KEY (Student) VALUE (grade) NVALUE (latest grade) DATE (date) MM
Zhang San 72 72 2021/11/12 1
Li Si 91 91 2021/11/14 1

https://blog.csdn.net/qq_41708308/article/details/89374701
https://blog.csdn.net/qq_37816503/article/details/108408875

Guess you like

Origin blog.csdn.net/Maxiao1204/article/details/129245978