sql之Row_Number()

1. Concept

Assign a continuous integer to each row in the partition of the result set, and the row number starts with the row number of the first row in each partition.

grammar:

ROW_NUMBER()  OVER (
	[PARTITION BY partition_expression,...]
	ORDER BY sort_expression [ASC| DESC],..
	)
  • The PARTITION BY clause divides the result set into partitions. The ROW_NUMBER() function is applied to each partition separately and reinitializes the row number of each partition. The PARTITION BY clause is optional. If not specified, the entire result set is treated as a single partition.
  • The ORDER BY clause defines the logical order of the rows in each partition of the result set. This word is required.

Note:
When using windowing functions such as over, the execution of grouping and sorting in over is later than the execution of "where, group by, order by".

Two, SQLserver instance

1. Assign a serial number to each customer line:

SELECT ROW_NUMBER() OVER(
	ORDER BY first_name ) row_num,
	first_name,last_name,city
FROM Customers;

Implementation results:
Insert picture description here
2. Classified by city, assign a sequential integer to each customer, and reset the number when the city changes:

SELECT first_name,last_name,city,
	ROW_NUMBER() OVER (
	PARTITION BY city
	ORDER BY first_name) row_num
FROM Customers
ORDER BY city;

Insert picture description here
3. Use ROW_NUMBER() for paging.
Assuming that there are 10 rows per page, return the data of the second page (rows 11 to 20):

WITH cte_customers AS (
	SELECT ROW_NUMBER() OVER(
		ORDER BY first_name,last_name) row_num,
		custrmer_id,first_name,last_name
	FROM customers)
SELECT customer_id,first_name,last_name 
FROM cte_customers
WHERE row_num >20 AND row_num <=30;

Insert picture description here
4. Count the minimum amount of all orders of the customer, and count the customer's first purchase.
Idea: First group by customer, then sort by order time, and number, and
then find out the minimum price and number of each customer's purchase

WITH tabs as (
	SELECT ROW_NUMBER() OVER (
		PARTITON BY customerid 
		OEDER BY ordertime ) row_num,
		customerid,totalprice 
	FROM Orders)
select * from tabs where totalprice in (
	select MIN(totalprice) from tabs group by customerid
	)

Guess you like

Origin blog.csdn.net/hhhhhhenrik/article/details/98348762