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

5

我在一个需求中卡住了。可能很简单,但我却没有突破。

我有一个名为Audit_Info的审计表,记录所有表的审计信息。 一个表可以在同一业务日期上多次运行。我的要求是获取每个月最新的业务日期记录,最多持续5个月。可能会发生这样的情况,某个特定月份未运行该表。

表格格式如下

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

同样,在这里还有其他表格。我需要5个表格。
感谢您的帮助。
祝好, Amit 请查看高亮部分
3个回答

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

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

1

嗯,如果我理解正确,您可以使用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;

OP的要求是获取最新的business_date(而不是load_timestamp)。另外...where timestamp >= current timestamp...timestamp不是一个列名,而且带有空格的current timestamp也是不正确的。 - mauro
谢谢Gordon, 如果我的描述有误,请见附上的文件。 - user3901666
感谢大家的回复。 谢谢Dieter,得到了预期结果.. :) - user3901666

1
如果我理解正确,您想要在最近5个月的数据中每个月选择最大的日期。如果是这样,请按年和月进行分组,并使用max函数选择每个月的最大日期:
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

谢谢Fuzzy, 抱歉,如果我的描述有误导。 请查看附件。 - user3901666

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接