row_number() over(partition by... order by...)分组聚合排序
row_number() over(partition by... order by...)分组聚合排序
ROW_NUMBER() OVER(
[PARTITION BY column_1, column_2,…]
[ORDER BY column_3,column_4,…] [desc/asc]
)
PARTITION BY 分组通过
ORDER BY 排序通过
sqlserver用法示例
创建表
use dbo;
IF object_id('employee') is not null drop table employee;
create table employee(employee int, departid int,salary decimal(18,2));
insert into employee values(1,10,5500.00);
insert into employee values(2,10,4500.00);
insert into employee values(3,20,1900.00);
insert into employee values(4,20,4800.00);
insert into employee values(5,40,6500.00);
insert into employee values(6,40,14500.00);
insert into employee values(7,40,44500.00);
insert into employee values(8,50,6500.00);
insert into employee values(9,50,7500.00);
select * from employee;
employee | departid | salary |
---|---|---|
1 | 10 | 5500.00 |
2 | 10 | 4500.00 |
3 | 20 | 1900.00 |
4 | 20 | 4800.00 |
5 | 40 | 6500.00 |
6 | 40 | 14500.00 |
7 | 40 | 44500.00 |
8 | 50 | 6500.00 |
9 | 50 | 7500.00 |
先分组再排序(先排序partition by后面的,再排序order by后面的)
select
employee
,departid
,salary
,row_number() over(partition by departid order by salary) sno
from employee
结果
employee | departid | salary |
---|---|---|
2 | 10 | 4500.00 |
1 | 10 | 5500.00 |
3 | 20 | 1900.00 |
4 | 20 | 4800.00 |
5 | 40 | 6500.00 |
6 | 40 | 14500.00 |
7 | 40 | 44500.00 |
8 | 50 | 6500.00 |
9 | 50 | 7500.00 |