我有一个名为 person_list 的表。数据是,
Insert into person_list(person_allocation_id, person_id, created_datetime, boss_user_name, allocation_status_id) values
(111008, 1190016, '2021-01-05 11:09:25', 'Rajesh', '2'),
(111007, 1190015, '2020-12-12 09:23:31', 'Sushmita', '2'),
(111006, 1190014, '2020-12-11 10:48:26', '', '3'),
(111005, 1190014, '2020-12-10 13:46:15', 'Rangarao', '2'),
(111004, 1190014, '2020-12-10 13:36:10', '', '3');
这里 person_allocation_id 是主键。
person_id 可能会重复几次。
所有这些行都按 person_allocation_id 排序(按降序排列)
现在,我想过滤具有 allocation_status_id = '2' 的行,并且对于 person_id,boss_user_name 应该是非空的。
这里的困难是,如果 person_id 将 allocation_status_id = '3' 作为其最新状态(根据日期),我必须排除该行。
我无法理解如何将一行中的日期与前一行中的另一个日期进行比较。
所以最后我应该在我的最终结果集中只得到 2 行(person_allocation_id 是 111008 和 111007)。
不知何故,我在 Oracle 中实现了这一点。
select person_id, person_allocation_id, create_datetime, boss_user_name, allocation_status_id
from (
select person_id, person_allocation_id, create_datetime, boss_user_name, allocation_status_id,
rank() over (partition by person_id order by create_datetime desc) rnk
from person_list
where allocation_status_id = '2')
where rnk = 1;
但是,我需要这个用于 MySql DB。任何人,请帮忙?
谢谢。