当前位置:网站首页>Zero foundation self-study SQL course | window function
Zero foundation self-study SQL course | window function
2022-07-01 02:12:00 【Meow Ningyi】
Hello everyone , I'm Ning Yi .
Today is our first 24 course : Window function .
Window function , Also called OLAP(Online Anallytical Processing, On line analytical processing ), The database data can be analyzed and processed in real time .
Window function is a syntax function commonly used by data analysts , The interview is almost a must for a large factory .
This section belongs to the high-level content , It's hard to understand , We must knock on the computer by ourselves , Look at the effect .
Only in this way can we deepen our understanding . The previous course talked about how to install a database , You can check it on my homepage ~
Basic grammar
< Window function > OVER (
[PARTITION BY < Column name for grouping >] -- Optional
[ORDER BY < Column name for sorting >] -- Optional
)above < Window function > The location of , You can put the following two functions :
(1) Aggregate functions : Such as sum.avg,count,max,min etc. ;
(2) Special window functions : such as rank, dense_rank, row_number, I'll talk about it in detail .
We usually put window functions in select In the sentence .
1、 Aggregate functions
Window functions are also used for grouping and sorting , And aggregate functions +GROUP BY The effect is similar to . But the records generated by window functions will not be aggregated , Each row of data generates a record .
example : stay Scores In the score sheet , find Sid by 7-10 Of the students , And calculate the total score of each student to show .

SELECT
Sid,
SUM(score) AS " Total score "
FROM Scores
WHERE Sid BETWEEN 7 AND 10
GROUP BY Sid;
But the problem is , While we know the total score of students , I also want to know the specific score of each subject , This cannot be done with the above statement .
Why? ?
because SELECT If the following field is an existing column in the table , be GROUP BY Clause must also have this column .
So if you want to know the specific scores of each subject , stay SELECT We will add Cid、score Two , stay GROUP BY If these two columns are also added to the clause , It would be contrary to our topic .
This knowledge point we are in the 15 Make peace 16 I've emphasized everything , You can click the home page to learn more , Let's not talk about it now .
We want our colleagues to know the total score of students 、 Course number 、 fraction , You need to use the window function .
SELECT
Sid,Cid,score,
SUM(score) OVER (PARTITION BY Sid) AS " Total score "
FROM Scores
WHERE Sid BETWEEN 7 AND 10;
Supplementary knowledge :PARTITION BY The meaning of
PARTITION BY Partition means partition , Follow GROUP BY The meaning of grouping is similar .
If you don't write PARTITION BY, It means that the entire data set belongs to a partition .
For example, above us SQL sentence , If you omit PARTITION BY
SELECT
Sid,Cid,score,
SUM(score) OVER() AS " Total score "
FROM Scores
WHERE Sid BETWEEN 7 AND 10;It turns out that , Will calculate the total score of all students .

2、 Special window functions
Common special window functions are :
(1) Get data ranking :
ROW_NUMBER(): Regardless of the parallel ranking , For example, the top three scores are 88,88,77, The ranking is 1,2,3.
RANK(): If there is a row with parallel ranking , Will occupy the next place . For example, the top three scores are 88,88,77, The ranking is 1,1,3.
DEBSE_RANK(): If the row is tied , Don't occupy the next place . For example, the top three scores are 88,88,77, The ranking is 1,1,2.
example : stay Scores In the score sheet , find Sid by 7-10 Of the students , And calculate the ranking from high to low .
SELECT *,
ROW_NUMBER() OVER(
ORDER BY score DESC
) AS " ranking "
FROM Scores
WHERE Sid BETWEEN 7 AND 10;
Used above ROW_NUMBER() Window function , You can see the increase “ ranking ” This column . If you will ROW_NUMBER() Replace with RANK(), The return result is as follows :

(2) Get first or last :
FIRST_VALUE(< Name >): Get first place .
LAST_VALUE(< Name >): Get the last place .
example : stay Scores In the score sheet , find Sid by 7-10 Of the students , Get the highest score of each student .
SELECT *,
FIRST_VALUE(score) OVER(
PARTITION BY Sid
ORDER BY score DESC
) AS " Top grade "
FROM Scores
WHERE Sid BETWEEN 7 AND 10;
(3) Offset function :
LEAD(< Name >,< The number n>): Access the downward offset from the current line n Row data .
LAG(< Name >,< The number n>): Offset from current row access n Row data .
NTH_VALUE(< Name >,< The number n>): From the... In the result set N Row get data .
(4) Distribution function :
CUME_DIST(): Less than... In the group 、 Equal to current rank The number of rows for the value / The total number of rows in the group .
PERCENT_RANK(): Returns the percentage sort of each row of a column , Each line follows the formula (rank-1) / (rows-1) Calculate .
NTILE(< The number n>): Divide the result set into n Group , And show which group a piece of data is assigned to .
Homework : stay Scores Verify the offset function and distribution function in , See what results can be returned .
such as : Get the... Below 2 Line offset fraction .
SELECT *,
LEAD(score,2) OVER(
ORDER BY score DESC
) AS " Get the... Below 2 That's ok score value "
FROM Scores
WHERE Sid BETWEEN 7 AND 10;
We SQL The introductory to advanced courses are over . I will continue to go out later SQL Advanced courses , Include views 、 Indexes 、 Concurrent 、 Deadlock 、 trigger 、 event 、 Business 、 Stored procedure, etc .
Recording and broadcasting classes and live broadcasting classes will also keep up ~
边栏推荐
- Fix names in the table (first character uppercase, other lowercase)
- org.redisson.client.RedisResponseTimeoutException: Redis server response timeout (3000 ms)错误解决
- int和位数组互转
- 【2022年】江西省研究生数学建模方案、代码
- (summary I) Halcon Foundation's target finding features + becoming a regular
- 求两个线段公共部分的长度
- 機器學習10-信念貝葉斯分類器
- With one-stop insight into industry hot spots, the new function "traffic market" of feigua data station B is launched!
- halcon数组的一些使用
- (翻译)使用眉状文本提高标题点击率
猜你喜欢

软件开发中的上游和下游

Int and bit group turn to each other

PMP是什麼?

【JS】【掘金】获取关注了里不在关注者里的人

Batch import of Excel data in applet

CorelDRAW 2022 Chinese Simplified 64 bit direct download
The latest CSDN salary increase technology stack in 2022 overview of APP automated testing

最新微信ipad协议 CODE获取 公众号授权等

LabVIEW calculates the camera image sensor resolution and lens focal length

A preliminary understanding of operator overloading
随机推荐
[graduation season · advanced technology Er] - summary from graduation to work
【做题打卡】集成每日5题分享(第一期)
Laravel event & subscription
修复表中的名字(首字符大写,其他小写)
What is PMP?
Log4j2 ThreadContext日志链路追踪
Short video platform development, relying on drawerlayout to achieve side sliding menu effect
Ernie-gram, 显式、完备的 n-gram 掩码语言模型,实现了显式的 n-gram 语义单元知识建模。
SWT/ANR问题--AMS/WMS
@ConfigurationProperties和@Value的区别
运算符重载的初识
如何在智汀中實現智能鎖與燈、智能窗簾電機場景聯動?
VirtualBox 安装增强功能
Open source basic software companies, looking for you to create the future together (api7.ai)
RocketQA:通过跨批次负采样(cross-batch negatives)、去噪的强负例采样(denoised hard negative sampling)与数据增强(data augment
Winodws 快速添加开机启动项
零基础自学SQL课程 | 窗口函数
模板:全局平衡二叉树
【2022年】江西省研究生数学建模方案、代码
What are the applications of SMS in enterprises?