SQL Join one to many 从满足条件的相同键值组中提取值

SQL Join one to many extract value from group of same key value where condition is met

我有两个 table 我想加入一对多关系。 parent table 具有与 child table 共享的唯一键值。 child table 保留该键的历史记录,因此有多个记录。示例如下。

我需要的是提取一个警报 ID 的工作人员名称,其中对于具有相同警报 ID 的给定组,操作是 'Alert Closed'。如果该组相同的警报 ID 没有带有 action = 'Alert Closed' 的记录,则采用具有最新时间戳的工作人员名称。我缺乏关于如何比较时间戳列的知识,当 'Alert Closed' 为真时我仍然得到重复项。

Table 1

alert_id            
---------
123         
456         
537         

Table 2

alert_id    worker_name action          timestamp
---------------------------------------------------------
123         system      Alert Created   8/6/2016  8:05:26 
123         james bond  Alert Opened    8/6/2016  8:05:30
123         james bond  Alert Closed    8/6/2016  8:05:35
123         james bond  Record updated  8/6/2016  8:05:35
456         system      Alert Created   8/6/2016  8:05:26
456         admin       Alert updated   8/6/2016  8:06:14
537         system      alert created   8/6/2016  8:07:20
537         Mary hill   Alert Closed    8/6/2016  8:08:26

结果 table 应该是:

alert_id    worker_name     
-----------------------
123         james bond      
456         admin       
537         Mary Hill       

这是一个优先查询。您可以使用 row_number() 来接近它。诀窍是正确排序:

select t2.*
from (select t2.*,
             row_number() over (partition by alert_id
                                order by (case when action = 'Alert Closed' then 1 else 2 end),
                                         timestamp desc
                               ) as seqnum
      from t2
     ) t2
where seqnum = 1;