Home Database Mysql Tutorial Detailed explanation of the use of Partition By and row_number functions in SQL Server

Detailed explanation of the use of Partition By and row_number functions in SQL Server

Jul 24, 2020 pm 05:39 PM

Detailed explanation of the use of Partition By and row_number functions in SQL Server

partition The by keyword is part of the analytic function. It is different from the aggregate function in that it can return multiple records in a group, while the aggregate function generally only has one record that reflects statistics. Records of values, partition by is used to group the result set. If not specified, it treats the entire result set as a group.

I saw a question in the group today, and I’ll summarize it here: Query the latest records under different categories. Isn't it very simple at first glance? If you want to classify, use Group By; if you want the latest record, use Order By. Then try to make it in your own table:

Related learning recommendations: mysql video tutorial

First of all, I put the data in the table Listed in reverse order of submission time:

"corp_name" is the GUID of the category (please forgive the arbitrariness of my naming). OK, here we add Group By according to the original idea to see the display effect:

Uh, um. This result is different from what I imagined. It seems that when writing code, you still need to analyze the problem rationally. Your mind cannot control the result!

Since the requirements are different categories of data, besides using Group By, are there any other functions that can be used? I did some research and found out that there is indeed an over (partition by) function. So what is the difference between it and the usually used Group By? In addition to simply grouping results, Group By is generally used together with aggregate functions. Partition By also has a grouping function and is an Oracle analysis function. I won’t go into details here.

Look at the code:

##over(partition by corp_name order by submit_time desc) as t. It is classified according to corp_name and sorted out in reverse order of time. The column "t" here is the number of occurrences of different corp_name classes. The requirement is to only query the latest submission data of different categories, then we only need to filter again for "t". :

Okay, the results are out. I don’t ask you to like them, but I just want you to give me a thumbs up if you look at the breasts in my avatar. May this good man have a safe life! ! !

ps: Detailed explanation of the use of SQL Server database partition by and ROW_NUMBER() functions

Some usage experience of SQL partition by field

Read first Example:

if object_id('TESTDB') is not null drop table TESTDB
create table TESTDB(A varchar(8), B varchar(8))
insert into TESTDB
select 'A1', 'B1' union all
select 'A1', 'B2' union all
select 'A1', 'B3' union all
select 'A2', 'B4' union all
select 'A2', 'B5' union all
select 'A2', 'B6' union all
select 'A3', 'B7' union all
select 'A3', 'B3' union all
select 'A3', 'B4'
Copy after login

-- All information

SELECT * FROM TESTDB
A  B
-------
A1 B1
A1 B2
A1 B3
A2 B4
A2 B5
A2 B6
A3 B7
A3 B3
A3 B4
Copy after login

-- After using the PARTITION BY function

SELECT *,ROW_NUMBER() OVER(PARTITION BY A ORDER BY A DESC) NUM FROM TESTDB
A  B  NUM
-------------
A1 B1 1
A1 B2 2
A1 B3 3
A2 B4 1
A2 B5 2
A2 B6 3
A3 B7 1
A3 B3 2
A3 B4 3
Copy after login

, you can see that there is an extra column of NUM in the result. This NUM shows the same The number of rows, for example, if there are 3 A1s, he will mark the number of each A1.

-- Just use the result of ROW_NUMBER() OVER

SELECT *,ROW_NUMBER() OVER(ORDER BY A DESC)NUM FROM TESTDB
 A  B   NUM
------------------------
A3 B7  1
A3 B3  2
A3 B4  3
A2 B4  4
A2 B5  5
A2 B6  6
A1 B1  7
A1 B2  8
A1 B3  9
Copy after login

You can see that it just marks the line number.

-- A deeper application

SELECT A = CASE WHEN NUM = 1 THEN A ELSE '' END,B
FROM (SELECT A,NUM = ROW_NUMBER() OVER(PARTITION BY A ORDER BY A DESC) FROM TESTDB) T
A  B
---------
A1 B1
  B2
  B3
A2 B4
  B5
  B6
A3 B7
  B3
  B4
Copy after login

Next, we will introduce the use of ROW_NUMBER() function one by one through several examples.

The examples are as follows:

1. Use the row_number() function for numbering, such as

select email,customerID, ROW_NUMBER() over(order by psd) as rows from QT_Customer
Copy after login

Principle: Sort by psd first, After sorting, number each piece of data.

2. Sort the order in ascending order of price, and sort each record with the following code:

select DID,customerID,totalPrice,ROW_NUMBER() over(order by totalPrice) as rows from OP_Order
Copy after login

3. Count each record All orders from each household are sorted in ascending order by the amount of each customer's order, and each customer's order is numbered. In this way, you will know how many orders each customer has placed. As shown in the picture:

The code is as follows:

select ROW_NUMBER() over(partition by customerID order by totalPrice) as rows,customerID,totalPrice, DID from OP_Order
Copy after login

4. Count the number of times each customer’s recent order was placed. Order.

The code is as follows:

 with tabs as 
( 
select ROW_NUMBER() over(partition by customerID order by totalPrice) as rows,customerID,totalPrice, DID from OP_Order 
 ) 
select MAX(rows) as '下单次数',customerID from tabs group by customerID
Copy after login

5. Count the minimum purchase amount among all orders of each customer, and also count the changes in the orders. How many times did the customer purchase?

如图:

上图:rows表示客户是第几次购买。

思路:利用临时表来执行这一操作。

1.先按客户进行分组,然后按客户的下单的时间进行排序,并进行编号。

2.然后利用子查询查找出每一个客户购买时的最小价格。

3.根据查找出每一个客户的最小价格来查找相应的记录。

代码如下:

with tabs as 
 ( 
select ROW_NUMBER() over(partition by customerID order by insDT) as rows,customerID,totalPrice, DID from OP_Order 
) 
 select * from tabs 
where totalPrice in  
( 
select MIN(totalPrice)from tabs group by customerID 
 )
Copy after login

6.筛选出客户第一次下的订单。

思路。利用rows=1来查询客户第一次下的订单记录。

代码如下:

with tabs as 
( 
select ROW_NUMBER() over(partition by customerID order by insDT) as rows,* from OP_Order 
) 
select * from tabs where rows = 1 
select * from OP_Order
Copy after login

7.rows_number()可用于分页

思路:先把所有的产品筛选出来,然后对这些产品进行编号。然后在where子句中进行过滤。

8.注意:在使用over等开窗函数时,over里头的分组及排序的执行晚于“where,group by,order by”的执行。

如下代码:

select  
ROW_NUMBER() over(partition by customerID order by insDT) as rows, 
customerID,totalPrice, DID 
from OP_Order where insDT>'2011-07-22'
Copy after login

以上代码是先执行where子句,执行完后,再给每一条记录进行编号。

The above is the detailed content of Detailed explanation of the use of Partition By and row_number functions in SQL Server. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1246
24
MySQL: Simple Concepts for Easy Learning MySQL: Simple Concepts for Easy Learning Apr 10, 2025 am 09:29 AM

MySQL is an open source relational database management system. 1) Create database and tables: Use the CREATEDATABASE and CREATETABLE commands. 2) Basic operations: INSERT, UPDATE, DELETE and SELECT. 3) Advanced operations: JOIN, subquery and transaction processing. 4) Debugging skills: Check syntax, data type and permissions. 5) Optimization suggestions: Use indexes, avoid SELECT* and use transactions.

MySQL's Role: Databases in Web Applications MySQL's Role: Databases in Web Applications Apr 17, 2025 am 12:23 AM

The main role of MySQL in web applications is to store and manage data. 1.MySQL efficiently processes user information, product catalogs, transaction records and other data. 2. Through SQL query, developers can extract information from the database to generate dynamic content. 3.MySQL works based on the client-server model to ensure acceptable query speed.

Explain the role of InnoDB redo logs and undo logs. Explain the role of InnoDB redo logs and undo logs. Apr 15, 2025 am 12:16 AM

InnoDB uses redologs and undologs to ensure data consistency and reliability. 1.redologs record data page modification to ensure crash recovery and transaction persistence. 2.undologs records the original data value and supports transaction rollback and MVCC.

MySQL: An Introduction to the World's Most Popular Database MySQL: An Introduction to the World's Most Popular Database Apr 12, 2025 am 12:18 AM

MySQL is an open source relational database management system, mainly used to store and retrieve data quickly and reliably. Its working principle includes client requests, query resolution, execution of queries and return results. Examples of usage include creating tables, inserting and querying data, and advanced features such as JOIN operations. Common errors involve SQL syntax, data types, and permissions, and optimization suggestions include the use of indexes, optimized queries, and partitioning of tables.

MySQL's Place: Databases and Programming MySQL's Place: Databases and Programming Apr 13, 2025 am 12:18 AM

MySQL's position in databases and programming is very important. It is an open source relational database management system that is widely used in various application scenarios. 1) MySQL provides efficient data storage, organization and retrieval functions, supporting Web, mobile and enterprise-level systems. 2) It uses a client-server architecture, supports multiple storage engines and index optimization. 3) Basic usages include creating tables and inserting data, and advanced usages involve multi-table JOINs and complex queries. 4) Frequently asked questions such as SQL syntax errors and performance issues can be debugged through the EXPLAIN command and slow query log. 5) Performance optimization methods include rational use of indexes, optimized query and use of caches. Best practices include using transactions and PreparedStatemen

Why Use MySQL? Benefits and Advantages Why Use MySQL? Benefits and Advantages Apr 12, 2025 am 12:17 AM

MySQL is chosen for its performance, reliability, ease of use, and community support. 1.MySQL provides efficient data storage and retrieval functions, supporting multiple data types and advanced query operations. 2. Adopt client-server architecture and multiple storage engines to support transaction and query optimization. 3. Easy to use, supports a variety of operating systems and programming languages. 4. Have strong community support and provide rich resources and solutions.

MySQL vs. Other Programming Languages: A Comparison MySQL vs. Other Programming Languages: A Comparison Apr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

How does MySQL index cardinality affect query performance? How does MySQL index cardinality affect query performance? Apr 14, 2025 am 12:18 AM

MySQL index cardinality has a significant impact on query performance: 1. High cardinality index can more effectively narrow the data range and improve query efficiency; 2. Low cardinality index may lead to full table scanning and reduce query performance; 3. In joint index, high cardinality sequences should be placed in front to optimize query.

See all articles