如何获取最后两行

时间:2014-02-18 17:07:31

标签: 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    // this associate is the last  for event 1
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     // this associate is the last  for event 2
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     // this associate is the last for event 3

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

  event_id      event_associate      rn
    1             steve             2
    1             paul              1
    2             paul              2
    2             ben               1
    3             steve             2
    3             ben               1

我试过

SELECT t.* , ROW_NUMBER() OVER (PARTITION BY event_associate ORDER BY event_date DESC) rn 
FROM mytable t
QUALIFY rn < 3

2 个答案:

答案 0 :(得分:1)

您必须计算数据库中的行数,然后使用此查询

        sql=sql+" LIMIT "+NumberOfRowsToShowInTables+" OFFSET "+(countrow-         NumberOfRowsToShowInTables);

其中countrow是数据库中的行数

如上所述,

NumberOfRowsToShowInTables等于2 sql是您的正常查询,没有限制

答案 1 :(得分:1)

每个活动

- &gt; PARTITION BY event_id

“最后但只有一个” - &gt; ORDER BY event_date DESC