当前位置:网站首页>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 productGet 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 .
边栏推荐
- China's crude oil heater market trend report, technological innovation and market forecast
- China microporous membrane filtration market trend report, technological innovation and market forecast
- Research Report on micro vacuum pump industry - market status analysis and development prospect prediction
- Research Report on market supply and demand and strategy of China's Plastic Geogrid industry
- I did a craniotomy experiment: talk about macromolecule coding theory and Lao Wang's fallacy from corpus callosum and frontal leukotomy
- Share the easy-to-use fastadmin open source system - Installation
- Research Report on plastic antioxidant industry - market status analysis and development prospect forecast
- Construction and maintenance of business websites [6]
- Import a large amount of data to redis in shell mode
- Analysis of enterprise financial statements [2]
猜你喜欢

Go language learning summary (5) -- Summary of go learning notes

It is said that this year gold three silver four has become gold one silver two..

Report on investment development and strategic recommendations of China's vibration isolator market, 2022-2027

Check the confession items of 6 yyds
![[shutter] statefulwidget component (bottom navigation bar component | bottomnavigationbar component | bottomnavigationbaritem component | tab switching)](/img/a7/0b87fa45ef2edd6fac519b40adbeae.gif)
[shutter] statefulwidget component (bottom navigation bar component | bottomnavigationbar component | bottomnavigationbaritem component | tab switching)

26 FPS video super-resolution model DAP! Output 720p Video Online
![[error record] the command line creates an error pub get failed (server unavailable) -- attempting retry 1 in 1 second](/img/6e/c82ff02a249b5d275a4589120a197a.jpg)
[error record] the command line creates an error pub get failed (server unavailable) -- attempting retry 1 in 1 second

Hot backup routing protocol (HSRP)
![[CV] Wu Enda machine learning course notes | Chapter 12](/img/c8/9127683b6c101db963edf752ffda86.jpg)
[CV] Wu Enda machine learning course notes | Chapter 12

The metamask method is used to obtain account information
随机推荐
Construction and maintenance of business website [3]
This team with billions of data access and open source dreams is waiting for you to join
Analysis of enterprise financial statements [3]
Redis -- three special data types
Go cache of go cache series
[shutter] statefulwidget component (image component | textfield component)
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of shock absorber oil in the global market in 2022
Research Report on the overall scale, major manufacturers, major regions, products and applications of outdoor vacuum circuit breakers in the global market in 2022
Construction and maintenance of business websites [9]
Common routines of compressed packets in CTF
How is LinkedList added?
I drew a Gu ailing with characters!
Today, I met a Alipay and took out 35K. It's really sandpaper to wipe my ass. it's a show for me
rwctf2022_ QLaaS
Go language learning summary (5) -- Summary of go learning notes
AMD's largest transaction ever, the successful acquisition of Xilinx with us $35billion
[dynamic planning] p1220: interval DP: turn off the street lights
Accounting regulations and professional ethics [19]
Construction and maintenance of business websites [8]
Construction and maintenance of business websites [4]