2016-02-23 64 views
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张桌子。

感谢您的帮助。

问候, 阿米特Please see the highlighted

回答

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; 
+0

OP要求是最新的** business_date **(不是load_timestamp)。另外...'where timestamp> =当前时间戳...':'时间戳记'不是一个列,'当前时间戳记'(有空格)是不正确的。 – mauro

+0

谢谢Gordon, 对不起,如果我的desc是误导性的。请找到附件 – user3901666

+0

感谢大家的回复 感谢Dieter ..got预期结果.. :) – 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 
+0

谢谢模糊, 对不起,如果我的desc误导。 请找到附件。 – user3901666

相关问题