0

我有一个名为 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。任何人,请帮忙?

谢谢。

4

2 回答 2

1
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 != '')。

于 2021-01-12T08:34:04.913 回答
1

您可以使用相关子查询来获取allocation_status_id每个的最新值person_id

select person_allocation_id   
   , person_id
   , created_datetime
   , boss_user_name
   , allocation_status_id
from (   
   select person_allocation_id   
      , person_id
      , created_datetime
      , boss_user_name
      , allocation_status_id
      , (select pl2.allocation_status_id
         from person_list pl2
         where pl2.person_id = pl.person_id
         order by pl2.created_datetime desc
         limit 1) latest_allocation_status_id
from person_list pl) t
where 
   allocation_status_id = '2' and latest_allocation_status_id <> '3' 
     and boss_user_name <> ''

外部查询能够检查最新状态并返回预期的结果集。该查询适用于 MySQL 5.7

演示在这里

附带说明一下,对于 MySQL 8.0,您可以用窗口函数替换相关子查询:

last_value(allocation_status_id) over (partition by person_id 
                                       order by created_datetime desc)

窗口函数演示

于 2021-01-12T08:37:22.147 回答