2016-12-21 42 views
0

我有一堆風險數字,每次計算數字時都會得到處理,因此每天可能會有2個或更多的風險數字。每次計算時都會存儲一個運行ID。SQL Server Top Run ID

我怎樣才能獲得11月份的最高ID的風險編號?

我嘗試此查詢:

select a.ptf_id,a.analysis_date, a.report_run_id, a.bps 
from rpt.rm_Report_History a 
where a.ptf_id=336 
and a.criteria_Set = 'Daily' 
and a.report_section_group = 'Key_Risk_Figures' 
and a.rm_rcp_param_name = 'Fund' 
and a.stat_class = 'standaloneVaR' 
and a.analysis_date>'2016-10-28' 

這給下面的輸出:

enter image description here

+0

是什麼*風險號碼*更大?什麼決定了*頂部*? – GurV

+0

最高運行ID是給定投資組合的最新風險編號,在這種情況下投資組合336 – Patrick

回答

0

如果你想爲每個日期的值,然後row_number()想到:

select a.* 
from (select a.ptf_id, a.analysis_date, a.report_run_id, a.bps, 
      row_number() over (partition by a.analysis_date order by a.report_run_id desc) as seqnum 
     from rpt.rm_Report_History a 
     where a.ptf_id = 336 and 
      a.criteria_Set = 'Daily' and 
      a.report_section_group = 'Key_Risk_Figures' and 
      a.rm_rcp_param_name = 'Fund' and 
      a.stat_class = 'standaloneVaR' and 
      a.analysis_date >= '2016-11-01' and 
      a.analysis_date < '2016-12-01' 
    ) a 
where seqnum = 1; 

我不確定你如何定義「Novem BER」。以上使用日曆月份。

+0

這返回1行,11月29日 – Patrick

+0

這是不是你想要的? [這個問題]的最佳答案(http://meta.stackoverflow.com/questions/333952/why-should-i-provide-an-mcve-for-what-seems-to-me-to-be-a -very-simple-sql-query)包含發佈SQL問題的一些重要提示。 –

+0

對於每個日期,我需要對應頂級ID – Patrick

0

試試這個,我也沒有非常瞭解你的需求肯定,但如果你想從TOP 1run_id從給定條件的記錄

select a.ptf_id,a.analysis_date, a.report_run_id, a.bps 
from rpt.rm_Report_History a 
inner join (select max(run_id) as run_id 
     from rpt.rm_Report_History a 
     where a.ptf_id=336 
     and a.criteria_Set = 'Daily' 
     and a.report_section_group = 'Key_Risk_Figures' 
     and a.rm_rcp_param_name = 'Fund' 
     and a.stat_class = 'standaloneVaR' 
     and a.analysis_date>'2016-10-28') b on b.run_id = a.run_id 
如果你想檢索十一月的數據只有使用

between> AND <如下否則將返回添加數據,其中分析日期晚於規定日期

and a.analysis_date between '2016-09-01' AND '2016-09-30' 
OR 
and a.analysis_date >= '2016-09-01' AND a.analysis_date <= '2016-09-30'