场景:数据库中id、toapp、topin、toclienttype几个字段都相同,receivetime字段不一样,现需要将receive最小的一行查出,其他行舍去。
select
*
from
(
select
*,
row_number() over(partition by id order by receivetime asc) num
from
xxxxxxxxxxxxxxxxxxxx
where
dt = '2019-01-14'
and toapp = 'xxxxxx'
and toclienttype = 'xxxxxx'
and msgrectype = '1'
and systemtime is not null
) as t
where
t.num = 1
这里主要的代码就是row_number() OVER (PARTITION BY COL1 ORDER BY COL2)
这行代码的意思是先对COL1列进行分组,然后按照COL2进行排序,row_number()函数是对分组后的每个组内记录按照COL2排序标号,我们最后取的时候就拿标号为1的一条记录,即达到我的需求。
例子:
empid deptid 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
row_number() OVER (PARTITION BY deptid ORDER BY salary)
SELECT *, Row_Number() OVER (partition by deptid ORDER BY salary desc) rank FROM employee
结果:
empid deptid salary rank
----------- ----------- --------------------------------------- --------------------
1 10 5500.00 1
2 10 4500.00 2
4 20 4800.00 1
3 20 1900.00 2
7 40 44500.00 1
6 40 14500.00 2
5 40 6500.00 3
9 50 7500.00 1
8 50 6500.00 2
在数据库中存在id、toapp、topin、toclienttype字段相同的多条记录,通过row_number() OVER (PARTITION BY COL1 ORDER BY COL2)窗口函数,可以按特定字段对这些重复记录进行分组并排序,选取每组中receivetime最小的一条记录,从而实现需求。示例展示了在员工表中按照部门deptid对薪水salary进行降序排序,获取每个部门薪水最高的员工。

7733

被折叠的 条评论
为什么被折叠?



