当前位置:网站首页>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 minimally invasive medical robot industry - market status analysis and development prospect prediction
- Research Report on the overall scale, major manufacturers, major regions, products and applications of battery control units in the global market in 2022
- Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of voltage source converters in the global market in 2022
- China Indonesia advanced wound care market trend report, technological innovation and market forecast
- Analyze comp-206 advanced UNIX utils
- It is said that this year gold three silver four has become gold one silver two..
- 5 environment construction spark on yarn
- Construction and maintenance of business website [1]
- [shutter] statefulwidget component (bottom navigation bar component | bottomnavigationbar component | bottomnavigationbaritem component | tab switching)
- Analysis of enterprise financial statements [4]
猜你喜欢
How is LinkedList added?
qwb2018_ core kernel_ rop
The metamask method is used to obtain account information
[shutter] statefulwidget component (pageview component)
[shutter] statefulwidget component (create statefulwidget component | materialapp component | scaffold component)
Common routines of compressed packets in CTF
[shutter] shutter layout component (opacity component | clipprect component | padding component)
How does esrally perform simple custom performance tests?
Detailed upgrade process of AWS eks
Huawei Hongmeng watch achieves fireworks display effect on New Year's Eve
随机推荐
Construction and maintenance of business website [3]
Construction and maintenance of business websites [6]
[error record] the command line creates an error pub get failed (server unavailable) -- attempting retry 1 in 1 second
Internal/validators js:124 throw new ERR_ INVALID_ ARG_ Type (name, 'string', value) -- solution
Huawei Hongmeng watch achieves fireworks display effect on New Year's Eve
China plastic bottle and container market trend report, technological innovation and market forecast
~91 rotation
Detailed upgrade process of AWS eks
Baidu sued a company called "Ciba screen"
Research Report on micro gripper industry - market status analysis and development prospect prediction
When Valentine's Day falls on Monday
[shutter] statefulwidget component (floatingactionbutton component | refreshindicator component)
I did a craniotomy experiment: talk about macromolecule coding theory and Lao Wang's fallacy from corpus callosum and frontal leukotomy
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 application segmentation of shock absorber oil in the global market in 2022
Web3js method to obtain account information and balance
[shutter] statefulwidget component (bottom navigation bar component | bottomnavigationbar component | bottomnavigationbaritem component | tab switching)
What is the difference between programming in real work and that in school?
Accounting regulations and professional ethics [18]
MySQL learning record (1)