Packet ordering function --row_number ()

1, MySQL8.0 above

Usage 1 : No packet ordering

Row_number () OVER (ORDER BY field DESC)
For example: Row_number () OVER (ORDER BY student achievement DESC)
represent, regardless of class, all students in grades from high to low sort
Usage 2: ordering packets
ROW_NUMBER () OVER (PARTITION BY field 1 ORDER BY DESC field 2)
shows a field of a packet field within a packet according to the sort 2, the calculated value of the function indicates that the order number after each internal sorting
e.g. : ROW_NUMBER () OVER (PARTITION BY student performance class oRDER BY DESC)
shows a "class" group, in each "class" the inner "student performance" sort, the function value is calculated in a rear internal sorting each
order No
explanation:
the ROW_NUMBER () play a number of features
partition by partition of the same data
order by a certain order so that the data sorted

2, MySQL5.7 version

Usage 1 : No packet ordering

For example: calculate the sales of the sales staff, the results in descending order, the query results to be included in the sales rankings

SET @rank := 0;
SELECT
A.*,
@rank := @rank + 1 AS rank 
FROM
( SELECT sales_name, sum( sales ) FROM spm_order

GROUP BY sales_name

ORDER BY sum( sales ) DESC ) A

Usage 2 : packet sequencing

Example: To calculate the sales of salespeople in different cities;

Requirements: According to the results of the sales staff in different cities to sort grouping (descending) sales, and the query results to include grouping ranking

SET @r := 0,
@type := '';
SELECT
 @r :=
CASE WHEN @type = a.sales_name THEN
@r + 1 ELSE 1
END AS rowNum,
 @type := a.sales_name AS type,
  a.*
FROM
( SELECT sales_name, city, sum( sales ) FROM spm_order

GROUP BY sales_name, city

ORDER BY sales_name, sum( sales ) DESC ) a;

 

Guess you like

Origin www.cnblogs.com/liuxiaomin/p/11958788.html