当前位置:网站首页>SQL learning window function
SQL learning window function
2022-04-23 13:45:00 【Du Xiaorui】
The window function is also called OLAP function .OLAP yes OnLine AnalyticalProcessing For short , It means real-time analysis and processing of database data .
The general form of window function :
< Window function > OVER ([ PARTITION BY < Name >]
ORDER BY
< Column names for sorting >)
- PARTITON BY Is used to group , That is, select which window you want to see , Be similar to GROUP BY Clause grouping function , however PARTITION BY Clause does not have GROUP BY The summary function of clause , It does not change the number of rows recorded in the original table .
- ORDER BY It's used to sort , That is, in the decision window , According to that rule ( Field ) To sort .
for instance :
SELECT
product_name,
product_type,
sale_price,
RANK() OVER ( PARTITION BY product_type ORDER BY sale_price ) AS ranking
FROM
product
Here we use product_type Make a classification , Then sort the prices under each category .
Window function classification
Sort special window function
- RANK function
There is the same bit skip , Such as 1,2,2,4 - DENSE_RANK
Won't skip bits , Such as 1,1,1,2 - ROW_NUMBER
The same order will not appear , Even the same will be in different order
as follows :
SELECT
product_name,
product_type,
sale_price,
RANK() OVER ( ORDER BY sale_price ) AS ranking,
DENSE_RANK() OVER ( ORDER BY sale_price ) AS dense_ranking,
ROW_NUMBER() OVER ( ORDER BY sale_price ) AS row_num
FROM
product

The use of aggregate functions in Windows
Aggregate functions become cumulative when used in window functions :
SELECT
product_id,
product_name,
sale_price,
SUM( sale_price ) OVER ( ORDER BY product_id ) AS current_sum,
AVG( sale_price ) OVER ( ORDER BY product_id ) AS current_avg
FROM
product;

Calculate the moving average
SELECT
product_id,
product_name,
sale_price,
AVG( sale_price ) OVER ( ORDER BY product_id ROWS 2 PRECEDING ) AS moving_avg,
AVG( sale_price ) OVER ( ORDER BY product_id ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING ) AS moving_avg
FROM
product;
have access to PRECEDING and FOLLOWING To specify the scope of the aggregate function .
Like above ,ROWS 2 PRECEDING Indicates starting from the current line , Add the data of the first two lines of the current line , Then average .
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING Indicates the current line and the line before and after the current line , Then average .
give the result as follows :

GROUPING Operator
ROLLUP - Calculate total and subtotal
SELECT product_type
,regist_date
,SUM(sale_price) AS sum_price
FROM product
GROUP BY product_type, regist_date WITH ROLLUP

Exercises
5.1
The execution result of the following statement
SELECT product_id
,product_name
,sale_price
,MAX(sale_price) OVER (ORDER BY product_id) AS Current_max_price
FROM product
The execution result of this statement is the highest selling price in all current records from top to bottom .

5.2
Continue to use product surface , Calculate according to the registration date (regist_date) The sales unit price of each date in ascending order (sale_price) Total of . Sorting is required to set the registration date to NULL Of “ motion T T-shirt ” The record is at 1 position ( That is, think of it as earlier than other dates )
SELECT
product_id,
product_name,
sale_price,
sum( sale_price ) OVER (
ORDER BY
IF
( ISNULL( regist_date ), 0, 1 )) AS Current_sum_price
FROM
product;

5.3
Thinking questions
① The window function does not specify PARTITION BY What is the effect of ?
② Why is it that window functions can only be used in SELECT Used in clauses ? actually , stay ORDER BY Clause using the system does not report an error .
版权声明
本文为[Du Xiaorui]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230556584684.html
边栏推荐
- Static interface method calls are not supported at language level '5'
- MySQL [SQL performance analysis + SQL tuning]
- JS compares different elements in two arrays
- Get the attribute value difference between two different objects with reflection and annotation
- Analysis of unused index columns caused by implicit conversion of timestamp
- On the bug of JS regular test method
- innobackupex增量备份
- Small case of web login (including verification code login)
- PG library to view the distribution keys of a table in a certain mode
- [point cloud series] summary of papers related to implicit expression of point cloud
猜你喜欢
![[point cloud series] full revolutionary geometric features](/img/00/701ba2f8130948329404dc4629ca46.png)
[point cloud series] full revolutionary geometric features

Double pointer instrument panel reading (I)

校园外卖系统 - 「农职邦」微信原生云开发小程序

切线空间(tangent space)

Detailed explanation of redis (Basic + data type + transaction + persistence + publish and subscribe + master-slave replication + sentinel + cache penetration, breakdown and avalanche)

Tangent space

【vmware】vmware tools 地址

Search ideas and cases of large amount of Oracle redo log

Short name of common UI control

Exemple de méthode de réalisation de l'action d'usinage à point fixe basée sur l'interruption de déclenchement du compteur à grande vitesse ob40 pendant le voyage de tia Expo
随机推荐
Core concepts of microservice architecture
The interviewer dug a hole for me: how many concurrent TCP connections can a single server have?
Small case of web login (including verification code login)
Detailed explanation of ADB shell top command
零拷贝技术
Processing of ASM network not automatically started in 19C
10g database cannot be started when using large memory host
Analysis of unused index columns caused by implicit conversion of timestamp
[barycentric coordinate interpolation, perspective correction interpolation] principle and usage opinions
Modification of table fields by Oracle
Oracle database combines the query result sets of multiple columns into one row
[point cloud series] full revolutionary geometric features
Dynamic subset division problem
Static interface method calls are not supported at language level '5'
Dolphin scheduler integrates Flink task pit records
SAP ui5 application development tutorial 72 - trial version of animation effect setting of SAP ui5 page routing
The query did not generate a result set exception resolution when the dolphin scheduler schedules the SQL task to create a table
RAC environment error reporting ora-00239: timeout waiting for control file enqueue troubleshooting
Use future and countdownlatch to realize multithreading to execute multiple asynchronous tasks, and return results after all tasks are completed
Dolphin scheduler configuring dataX pit records