2016-02-23 67 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

相關問題