当前位置:网站首页>Window sorting functions rank and deny for SQL data analysis_ rank、raw_ Number and lag, lead window offset function [usage sorting]
Window sorting functions rank and deny for SQL data analysis_ rank、raw_ Number and lag, lead window offset function [usage sorting]
2022-07-02 00:05:00 【Chung, boundless Eagle】
List of articles
Be careful : These functions must be in MySQL3.8 Version above can be used , Otherwise, there will be mistakes .
zero 、 Write it at the front
All the code in this article is in SQL ZOO Platform operation , Data is also available under the platform world Table and some data tables provided by other platforms , All the codes have passed the test .
One 、 Window sorting function
1、 Basics
- Standard grammar :over (partition by Field name order by Field name asc/desc)
- over() Two clauses are optional ,partition by Specify partition by ,order by Specify sort by
- Compare :
rank function : about 4,4,4,8, That is, if there is a row with parallel ranking , The ranking result is :1,1,1,4
dense_rank function : about 4,4,4,8, That is, if there is a row with parallel ranking , The ranking result is :1,1,1,2
row_number function : about 4,4,4,8, That is, if there is a row with parallel ranking , The ranking result is :1,2,3,4
2、rank() over()—— Skip sort
(1) explain
For example, the value is 99, 99, 90, 89, So through this
The ranking obtained by the function is 1, 1, 3, 4
Because the front 2 Both are first , And they all occupy a position .
(2) practice : The land area of each continent is larger than 100 ten thousand 、 The capital city is not named after A,M,C The first is the name of the continent and country in descending order of the population of each continent .( Countries with equal populations rank the same , But each occupies a position )
select continent,name,
rank() over(PARTITION BY continent ORDER BY population desc) RO
from world
where area>=1000000 and left(capital,1) not in ('A','M','C')
# stay SQL ZOO This sentence is sometimes needed on the practice platform :group by continent,name
# If it can be compiled normally, it doesn't matter

(3) Other conditions remain the same , If we only want to look at the top two countries on each continent , Now RO This naming works ( Sub query is needed ):
select RF.continent,RF.name
from (select continent,name,
rank() over(PARTITION BY continent ORDER BY population desc) as RO
from world
where area>=1000000 and left(capital,1) not in ('A','M','C')) as RF
where RF.RO=2
3、dense_rank() over()
(1) explain :dense. _rank(); Parallel continuous sort – For example, the value is 99, 99,90, 89,
Then the ranking obtained by this function is 1, 1, 2, 3
(2) practice : The query number is ’S14000024’ And the election year is 2017 Parties and votes sorted by election votes in .
select party,votes,
dense_rank() over(ORDER BY votes desc) as RO
from ge
where constituency='S14000024' and yr=2017
group by party,votes
order by party

4、raw_number() over()
(1) explain :row _number(): Continuous sort – For example, the value is 99, 99, 90, 89, That's right
The ranking obtained by this function is 1, 2, 3, 4
Select the corresponding sorting window function according to the demand for sorting value , Due to the different characteristics of values ( For example, the value does not repeat ) , These three functions can be used in general
(2) practice : The query date is ’2020-4-25’ All names and dates of diagnosis , List their diagnosis date and death date in descending order
select name,confirmed,
row_number() over(ORDER BY confirmed desc) RC
,deaths
,row_number() over(ORDER BY deaths desc) RD
from covid
where whn='2020-4-25'
order by confirmed desc;
5、 Be careful
1、 Window functions can only be used in select Used in clauses
2、 In the window function partition by Clause can specify the partition of data , and group by To regroup, the difference is ,partition by Only partition without de duplication
3、 There is no partition by When clause , That is, no data partition , Directly divide the whole table into one area
4、 Sorting window function order by Clause is required , In window function order by Clause in partition , Sort the data rows according to the specified fields and sorting method
5、 The window function must have a name , For example, common RO,RI etc.
Two 、 Window offset function
1、lag()
lag( Field name , Offset , The default value is ) over()
select
name,
date_format(whn,'%Y-%m-%d') date,
confirmed The cumulative number of confirmed patients by the end of the day ,
lag(confirmed,1) over(partition by name order by whn) The cumulative number of confirmed cases as of yesterday ,
(confirmed-lag(confirmed,1) over(partition by name order by whn)) The number of newly diagnosed people every day
from covid
where name in ('France','Germany') and month(whn)=1
group by name,whn,confirmed
order by whn;
2、lead()
lead( Field name , Offset , The default value is ) over()
Allow us to partition from the window , According to the given forward offset relative to the current line (LAG) Or post offset (LEAD), And return the value of the corresponding row , The default offset is 1. When the specified offset is not matched, the line used is ,LAG and LEAD Default return NULL, Of course, other values can be used to replace LAG(val,1,0.00) The first 3 The first parameter is the replacement value .
3、 Comprehensive practice
select name,date_format(whn,'%Y-%m-%d') date,
confirmed - lag(confirmed,1) over(PARTITION BY name ORDER BY whn) Week_New
from covid
where name='Italy' and weekday(whn)=0
group by name,whn,confirmed
order by whn
confirmed The number of confirmed cases this Monday ,weekday(whn)=0 Select Monday ( Limit the calculation scope to Monday , Subtracting from each Monday is the addition of a week )
The article is summarized in elder martial brother zidai's course :https://www.bilibili.com/video/BV1ZM4y1u7uF?p=4, Some modifications and verifications have been made on the basis of this course .
边栏推荐
- 门级建模—课后习题
- It's nothing to be utilitarian!
- 【QT】QtCreator卸载与安装(非正常状态)
- ERP项目施行计划的目的是什么?
- 毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?
- Jielizhi, production line assembly link [chapter]
- SecurityUtils. getSubject(). How to solve the problem that getprincipal() is null
- 下载在线视频 m3u8使用教程
- 使用uni-simple-router,动态传参 TypeError: Cannot convert undefined or null to object
- const // It is a const object...class nullptr_t
猜你喜欢

Shell process control

Use pair to do unordered_ Key value of map
![[Qt] résoudre le problème que Qt msvc 2017 ne peut pas Compiler](/img/35/e458fd437a0bed4bace2d6d65c9ec8.png)
[Qt] résoudre le problème que Qt msvc 2017 ne peut pas Compiler

毕业季 | 华为专家亲授面试秘诀:如何拿到大厂高薪offer?

Correlation - intra group correlation coefficient

牛客-练习赛101-推理小丑

Write some suggestions to current and future doctoral students to sort out and share

【QT】QtCreator卸载与安装(非正常状态)

UDS bootloader of s32kxxx bootloader
Linux CentOS7安装Oracle11g的超完美新手教程
随机推荐
Leetcode medium question sharing (5)
Key points and difficulties of the course "information content security" at Harbin Institute of Technology
How to solve the image pop-up problem when pycharm calls Matplotlib to draw
一个实习生的CnosDB之旅
基于全志H3的QT5.12.9移植教程
[C #] dependency injection and Autofac
Windows 7 install MySQL error: 1067
使用htaccess文件禁止目录里的脚本执行权限
Overview of edge calculation
Digital transformation has a long way to go, so how to take the key first step
Shell custom function
LDR6035智能蓝牙音响可对手机设备持续充放电方案
Why does blocprovider feel similar to provider?
kubernetes资源对象介绍及常用命令(三)
Huawei HMS core joins hands with hypergraph to inject new momentum into 3D GIS
GCC compilation
北京炒股开户选择手机办理安全吗?
Multi table operation - one to one, one to many and many to many
Soft exam information system project manager_ Compiled abbreviations of the top ten management processes to help memory recitation - -- software test advanced information system project manager 054
SecurityUtils.getSubject().getPrincipal()为null的问题怎么解决