SQL Server Top Run ID

时间:2016-12-21 11:27:20

标签: sql sql-server

我有一堆风险数据,每次计算数字时都会被处理,因此每天可能有2个或更多的风险数字。每次计算它们时,都会存储一个运行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

2 个答案:

答案 0 :(得分: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;

我不确定你如何定义&#34; 11月和#34;的月份。以上使用日历月。

答案 1 :(得分:0)

尝试,我也不太确定您的要求,但是如果您希望来自给定条件的TOP 1 run_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

如果您只想检索11个数据,请使用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'