


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:
ps: Detailed explanation of the use of SQL Server database partition by and ROW_NUMBER() functions
Some usage experience of SQL partition by fieldRead 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'
SELECT * FROM TESTDB A B ------- A1 B1 A1 B2 A1 B3 A2 B4 A2 B5 A2 B6 A3 B7 A3 B3 A3 B4
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
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
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
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
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
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
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
如图: 上图:rows表示客户是第几次购买。 思路:利用临时表来执行这一操作。 1.先按客户进行分组,然后按客户的下单的时间进行排序,并进行编号。 2.然后利用子查询查找出每一个客户购买时的最小价格。 3.根据查找出每一个客户的最小价格来查找相应的记录。 代码如下: 6.筛选出客户第一次下的订单。 思路。利用rows=1来查询客户第一次下的订单记录。 代码如下: 7.rows_number()可用于分页 思路:先把所有的产品筛选出来,然后对这些产品进行编号。然后在where子句中进行过滤。 8.注意:在使用over等开窗函数时,over里头的分组及排序的执行晚于“where,group by,order by”的执行。 如下代码: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
)
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
select
ROW_NUMBER() over(partition by customerID order by insDT) as rows,
customerID,totalPrice, DID
from OP_Order where insDT>'2011-07-22'
以上代码是先执行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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



InnoDB's full-text search capabilities are very powerful, which can significantly improve database query efficiency and ability to process large amounts of text data. 1) InnoDB implements full-text search through inverted indexing, supporting basic and advanced search queries. 2) Use MATCH and AGAINST keywords to search, support Boolean mode and phrase search. 3) Optimization methods include using word segmentation technology, periodic rebuilding of indexes and adjusting cache size to improve performance and accuracy.

Full table scanning may be faster in MySQL than using indexes. Specific cases include: 1) the data volume is small; 2) when the query returns a large amount of data; 3) when the index column is not highly selective; 4) when the complex query. By analyzing query plans, optimizing indexes, avoiding over-index and regularly maintaining tables, you can make the best choices in practical applications.

Yes, MySQL can be installed on Windows 7, and although Microsoft has stopped supporting Windows 7, MySQL is still compatible with it. However, the following points should be noted during the installation process: Download the MySQL installer for Windows. Select the appropriate version of MySQL (community or enterprise). Select the appropriate installation directory and character set during the installation process. Set the root user password and keep it properly. Connect to the database for testing. Note the compatibility and security issues on Windows 7, and it is recommended to upgrade to a supported operating system.

The difference between clustered index and non-clustered index is: 1. Clustered index stores data rows in the index structure, which is suitable for querying by primary key and range. 2. The non-clustered index stores index key values and pointers to data rows, and is suitable for non-primary key column queries.

Article discusses popular MySQL GUI tools like MySQL Workbench and phpMyAdmin, comparing their features and suitability for beginners and advanced users.[159 characters]

Article discusses strategies for handling large datasets in MySQL, including partitioning, sharding, indexing, and query optimization.

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 supports four index types: B-Tree, Hash, Full-text, and Spatial. 1.B-Tree index is suitable for equal value search, range query and sorting. 2. Hash index is suitable for equal value searches, but does not support range query and sorting. 3. Full-text index is used for full-text search and is suitable for processing large amounts of text data. 4. Spatial index is used for geospatial data query and is suitable for GIS applications.
