从多个组中选择第n个最近的行

时间:2016-07-06 18:21:11

标签: sql oracle oracle12c

使用Oracle 12c,我有一个表table1,如下所示:

ID    DATA1    DATA2    LAST_UPDATE_TIMESTAMP
1       1        2            time_stamp1
2       1        2            time_stamp2
3       2        1            time_stamp3
4       2        2            time_stamp4
5       1        2            time_stamp5
6       1        1            time_stamp6
7       2        2            time_stamp7
8       1        1            time_stamp8
9       2        1            time_stamp9
10      1        2            time_stamp10

DATA1DATA2只有四个可能的对:

1,1 1,2 2,1 2,2

如果按LAST_UPDATE_TIMESTAMP排序,这是第n个最近的记录,如何获取每对的ID?

例如,如果LAST_UPDATE_TIMESTAMP已经按降序排序,那么对于最近的,四对的ID将是1,3,4,6。对于最近的第二个,它将是2,7,8,9

解决方案

感谢@kordirko。这是我最终使用的SQL

SELECT ID
FROM (
SELECT t.*,
       row_number() 
       over (partition by data1, data2 
             ORDER BY last_updated_timestamp DESC) as rn
       FROM table1 t
)
WHERE rn = n --n means the nth most recent, starts from 1

2 个答案:

答案 0 :(得分:1)

如果只想返回一行,则可以使用fetch first子句(技术上称为“行限制子句”)。例如,要获得(1,1)的第五行:

select t.*
from table1 t
where data1 = 1 and data2 = 1
order by last_update_timestamp desc
offset 4
fetch next 1 row only;

请注意,offset在这种情况下为“4”而不是“5”,因为跳过四行才能到达第五行。为了提高性能,建议使用(data1, data2, last_upate_timestamp)的索引。

答案 1 :(得分:1)

尝试:

SELECT ID, DATA1, DATA2, LAST_UPDATE_TIMESTAMP,
       rn -- this is a number of pair: 1-first most recent, 2-second most recent etc.
FROM (
   SELECT t.*,
          row_number() 
             over (partition by data1, data2 
                   ORDER BY last_updated_timestamp DESC) as Rn
)
WHERE rn <= 5 -- where 5 is a limit ==> you will get at most 5 most recent records for each pair