ROW_NUMBER function
一、ROW_NUMBER OVER
- Syntax format:
row_number() over(partition by 分组列 order by 排序列 desc)
- Note: when row_number() over() function, the execution of grouping and sorting in over() is later than the execution of where, group by, and order by.
- Query case:
// 表
CREATE TABLE `User` (
`name` varchar(100) DEFAULT NULL,
`course` varchar(100) DEFAULT NULL,
`score` int(11) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
// 数据
INSERT INTO local_database.`User`
(name, course, score)
VALUES('wangwu', 'English', 60);
INSERT INTO local_database.`User`
(name, course, score)
VALUES('wangwu', 'Chinese', 50);
INSERT INTO local_database.`User`
(name, course, score)
VALUES('wangwu', 'Math', 55);
// 查询 --- 按照course分组
SELECT *, ROW_NUMBER() OVER(PARTITION BY u.course ORDER BY u.score) num FROM `User` u
// 查询结果
Id Name Course Score 排名
1002 张三 数学 90 1
1004 李四 数学 60 2
1007 王五 数学 30 3
1001 李四 英语 100 1
1008 张三 英语 60 2
1003 王五 英语 50 3
1000 张三 语文 80 1
1005 李四 语文 80 2
1006 王五 语文 50 3
Second, the difference between PARTITION BY and GROUP BY
-
the difference:
partition by(Analytical function) It returns every piece of data in the group, and can sort the grouped data;
group by(Aggregate function) can only return records of the data statistics of the group after aggregation. -
test:
// 查询 --- 按照name分组
SELECT *, ROW_NUMBER() OVER(PARTITION BY u.name ORDER BY u.score) num FROM `User` u
// 查询结果
Id Name Course Score num
1004 李四 数学 60 1
1005 李四 语文 80 2
1001 李四 英语 100 3
1007 王五 数学 30 1
1006 王五 语文 50 2
1003 王五 英语 50 3
1008 张三 英语 60 1
1000 张三 语文 80 2
1002 张三 数学 90 3
// 查询 --- 按照course分组
SELECT *, ROW_NUMBER() OVER(PARTITION BY u.course ORDER BY u.score) num FROM `User` u
// 查询结果
Id Name Course Score 排名
1002 张三 数学 90 1
1004 李四 数学 60 2
1007 王五 数学 30 3
1001 李四 英语 100 1
1008 张三 英语 60 2
1003 王五 英语 50 3
1000 张三 语文 80 1
1005 李四 语文 80 2
1006 王五 语文 50 3