如何改进最后一个?

时间:2014-02-17 22:23:11

标签: sql teradata

我有下表。我需要为每个事件获取最后一个事件关联

event_id    event_date  event_associate
1           2/14/2014   ben
1           2/15/2014   ben
1           2/16/2014   steve
1           2/17/2014   steve   // this associate is the last but one for event 1
1           2/18/2014   paul
2           2/19/2014   paul
2           2/20/2014   paul    // this associate is the last but one for event 2 
2           2/21/2014   ben
3           2/22/2014   paul
3           2/23/2014   paul
3           2/24/2014   ben
3           2/25/2014   steve   // this associate is the last but one for event 3
3           2/26/2014   ben

我需要找出每个事件的最后一个,但一个 event_associate 。结果应该是

event_id      event_associate
1             steve    
2             paul
3             steve

我知道为了做到这一点,我需要最大化 event_date 并排除最后的 event_associate

所以我试过

SELECT event_id , event_associate
WHERE NOT EXISTS (
SELECT *
FROM mytable
WHERE event_date = MAX(event_date)
)
QUALIFY ROW_NUMBER() OVER ( PARTITION BY  event_id ORDER BY event_date DESC) = 1

但我不知道在这种情况下如何使用EXISTS

1 个答案:

答案 0 :(得分:2)

你非常接近,你只需要基于ROW_NUMBER的第二行:

select t.*,
   row_number() 
   over (partition by event_id
         order by event_date desc)
from tab as t
qualify
   row_number() 
   over (partition by event_id
         order by event_date desc) = 2
-- or simply
-- qualify rn = 2