当前位置:网站首页>MySQL learning record (9)
MySQL learning record (9)
2022-07-02 21:30:00 【White_ Silence (Learning version)】
1. The concept of window function and its basic usage
The window function is also called OLAP function .OLAP yes OnLine AnalyticalProcessing For short , It means real-time analysis and processing of database data .
For the sake of understanding , It is called window function . The conventional SELECT Statements are used to query the whole table , The window function allows us to selectively summarize some data 、 Calculate and sort .
1.1 General form of window function
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 .
< Window function > OVER ([PARTITION BY < Name >]
ORDER BY < Column names for sorting >)
-- Example
select product_name,product_type,sale_price,
rank() over(partition by product_type
order by sale_price) as ranking
from product;
1.2 Types of window functions
One is take SUM、MAX、MIN Aggregate functions such as are used in window functions
Two is RANK、DENSE_RANK And other special window functions for sorting
1.2.1 Special window functions
- RANK function **( British sort )**
When calculating the sort , If there are records of the same order , be Will skip Next place .
example ) Yes 3 Record number one 1 When a :1 position 、1 position 、1 position 、4 position ……
- DENSE_RANK function **( Chinese sort )**
It's also sort by calculation , Even if there are records of the same rank , I won't skip Next place .
example ) Yes 3 Record number one 1 When a :1 position 、1 position 、1 position 、2 position ……
- ROW_NUMBER function
give The only consecutive bit .
example ) Yes 3 Record number one 1 When a :1 position 、2 position 、3 position 、4 position
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;
1.2.2 The use of aggregate functions on window functions
The use of aggregate function in windowing function is the same as the previous special window function , But the result is Cumulative Aggregate function value of .
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;
1.3 Application of window function - Calculate the moving average
PRECEDING(“ Before ”), Specify the frame as “ By the end of n That's ok ”, Add your own line
FOLLOWING(“ after ”), Specify the frame as “ Until after n That's ok ”, Add your own line
BETWEEN 1 PRECEDING AND 1 FOLLOWING, Specify the frame as “ Before 1 That's ok ” + “ after 1 That's ok ” + “ Oneself ”
< Window function > OVER (ORDER BY < Column names for sorting >
ROWS n PRECEDING )
< Window function > OVER (ORDER BY < Column names for sorting >
ROWS BETWEEN n PRECEDING AND n FOLLOWING)
SELECT product_id
,product_name
,sale_price
,sum(sale_price) over(order by product_id rows 2 preceding ) as move_sum
,avg(sale_price) over(order by product_id rows between 1 preceding
and 1 following) as move_avg
from product;
1.4 Application scope and precautions of window function
- In principle, , Window functions can only be used in SELECT Used in clauses .
- Window function OVER Medium ORDER BY Clause does not affect the sorting of the final results . It is only used to determine the order in which window functions are evaluated .
1.5 GROUPING Operator
1.5.1 ROLLUP - Calculate total and subtotal
The conventional GROUP BY You can only get the subtotal of each category , Sometimes you need to calculate Total of categories , It can be used ROLLUP keyword .
SELECT product_type
,regist_date
,SUM(sale_price) AS sum_price
FROM product
GROUP BY product_type, regist_date WITH ROLLUP
Exercises
Please name the... Used in this chapter product( goods ) The table is executed as follows SELECT The result of the statement .
SELECT product_id
,product_name
,sale_price
,MAX(sale_price) OVER (ORDER BY product_id) AS Current_max_price
FROM product
Get the maximum value of the scroll
Continue to use product surface , Calculate according to Registration date (regist_date) Ascending The sales unit price of each date arranged (sale_price) Of Total . 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
,regist_date
,sale_price
,sum(sale_price) OVER (ORDER BY regist_date) AS sum_date_price
FROM product;
Thinking questions
① The window function does not specify PARTITION BY What is the effect of ?
Don't specify , Make statistics from the first row to the current row ;
② 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 .
边栏推荐
- Research Report on the overall scale, major manufacturers, major regions, products and applications of hollow porcelain insulators in the global market in 2022
- Analysis of enterprise financial statements [1]
- Research Report on the overall scale, major manufacturers, major regions, products and applications of micro hydraulic cylinders in the global market in 2022
- In depth research and investment feasibility report on the global and China active vibration isolation market 2022-2028
- Research Report on the overall scale, major manufacturers, major regions, products and applications of battery control units in the global market in 2022
- [shutter] statefulwidget component (pageview component)
- Go web programming practice (2) -- process control statement
- Research Report on the overall scale, major manufacturers, major regions, products and applications of swivel chair gas springs in the global market in 2022
- Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of sound quality head simulators in the global market in 2022
- Construction and maintenance of business website [1]
猜你喜欢
[CV] Wu Enda machine learning course notes | Chapter 12
6 pyspark Library
[shutter] statefulwidget component (bottom navigation bar component | bottomnavigationbar component | bottomnavigationbaritem component | tab switching)
In depth research and investment feasibility report of global and Chinese isolator industry, 2022-2028
JDBC | Chapter 4: transaction commit and rollback
26 FPS video super-resolution model DAP! Output 720p Video Online
Check the confession items of 6 yyds
Customized Huawei hg8546m restores Huawei's original interface
Investment strategy analysis of China's electronic information manufacturing industry and forecast report on the demand outlook of the 14th five year plan 2022-2028 Edition
Talk about macromolecule coding theory and Lao Wang's fallacy from the perspective of evolution theory
随机推荐
Research Report on micro vacuum pump industry - market status analysis and development prospect prediction
Sword finger offer (I) -- handwriting singleton mode
[fluent] dart generic (generic class | generic method | generic with specific type constraints)
Interpretation of some papers published by Tencent multimedia laboratory in 2021
One week dynamics of dragon lizard community | 2.07-2.13
Analysis of enterprise financial statements [1]
Golang embeds variables in strings
Go web programming practice (2) -- process control statement
Construction and maintenance of business websites [10]
5 environment construction spark on yarn
Get weekday / day of week for datetime column of dataframe - get weekday / day of week for datetime column of dataframe
~90z axis translation
Research Report on market supply and demand and strategy of microplate instrument industry in China
JDBC | Chapter 4: transaction commit and rollback
Research Report on right-hand front door industry - market status analysis and development prospect forecast
China plastic bottle market trend report, technological innovation and market forecast
Internet Explorer ignores cookies on some domains (cannot read or set cookies)
Roommate, a king of time, I took care of the C language structure memory alignment
Research Report on the overall scale, major manufacturers, major regions, products and applications of micro hydraulic cylinders in the global market in 2022
Volvo's first MPV is exposed! Comfortable and safe, equipped with 2.0T plug-in mixing system, it is worth first-class