mysql - 通过过滤状态查找最新的行
问题描述
我有一个名为 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。任何人,请帮忙?
谢谢。
解决方案
SELECT t1.*
FROM person_list t1
JOIN ( SELECT MAX(t2.person_allocation_id) person_allocation_id, t2.person_id
FROM person_list t2
GROUP BY t2.person_id ) t3 USING (person_allocation_id, person_id)
WHERE t1.allocation_status_id = '2'
如果需要,向 WHERE 子句添加更多条件(例如,AND boss_user_name != ''
)。
推荐阅读
- oracle - 为什么游标在下面的 PLSQL 块中两次获取表中的特定值?
- angular - Angular Material排序无法对列进行排序
- oauth - 从 auth0 中的访问令牌获取用户名
- html - 我可以使用 Brython 获取网站的参数吗?
- poco - 如何在 Mac 上使用 Poco C++ 静态库
- javascript - 在切换条件下从数据集获取值的问题
- c - 分配和释放动态内存
- wso2 - 如何在 carbon/console 中默认启用用户定义的声明方言
- flutter - 为什么当页面向下滚动时列表视图中的图像会消失?
- express - 错误:无法获取/[QUASAR FRAMEWORK] [HEROKU 部署]