需要在分区中选择最新的 5 条记录

Need to pick latest 5 records among the partitions

我卡在了一个要求中。这可能很简单,但我没有通过。

我有一个审计 table Audit_Info,它捕获所有 table 的审计信息。 table 可以在同一营业日多次 运行。我的要求是获取最近 5 个月内每个月的最新营业日期记录。可能会发生某个特定月份的 table 不是 运行。

Table 就像

table_name business_date src_rec tgt_rec del_rec load_timestamp
abc          25/10/2015   10      10      0       23/01/2016 03:06:56
abc          25/10/2015   10      10      0       23/01/2016 05:23:34
abc          07/09/2015   10      10      0       23/10/2015 05:37:30
abc          05/08/2015   10      10      0       23/09/2015 05:23:34
abc          15/06/2015   10      10      0       23/07/2015 05:23:34
abc          25/04/2015   10      10      0       23/05/2015 05:23:34

类似地,这里还有其他 table。我需要 5 table 秒。

感谢您的帮助。

此致, 阿米特

嗯,如果我理解正确的话,你可以使用 row_number() 和一些日期算法:

select ai.*
from (select ai.*,
             row_number() over (partition by table_name, extract(year from business_date), extract(month from business_date)
                                order by business_date desc
                               ) as seqnum
      from audit_info ai
      where timestamp >= current timestamp - interval '5' month
     ) ai
where seqnum = 1;

如果我没理解错的话,您想要的是您拥有数据的最近 5 个月的每月最大日期。如果是这样,按年和月分组并使用 max 函数来 select 每个月的最大日期:

select top 5 
    max(business_date), extract(year from business_date) , extract(month from business_date)
from mytable
group by extract(year from business_date), extract(month from business_date)
order by extract(year from business_date) desc, extract(month from business_date) desc

根据您的预期结果,这应该很接近:

select * from tab
where  -- last five months
   business_date >= add_months(trunc(current_date),-5)
qualify
   row_number()  
   over (partition by trunc(business_date)  -- every month
         order by business_date desc, load_timestamp desc) -- latest date