我有许多不同的投资组合,每个投资组合都有自己的ID,而且这是带有run_id的风险编号
我想要做的是每个日期,拉出与每个投资组合的最大run_id链接的Bps号码
select analysis_date,ptf_id,stat_name,Bps,run_id
from rpt.rm_Report_History
where analysis_date > '20160102' and criteria_Set= 'Daily'
and ptf_id in( '10038','10039')
and report_section_group = 'Key_Risk_Figures'
and rm_rcp_param_name = 'Fund'
and stat_class = 'standaloneVaR'
,它提供以下输出
答案 0 :(得分:1)
这是一个带有子选择的解决方案,该子选择首先确定列表中的max run_id,然后选择具有条件AND max run_id的所有行。由于列不是唯一的,因此您可以使用GROUP BY
修饰符删除多个匹配项。
这是一个经典的最小/最大群体问题。有些DBMS有更好的解决方案,但下面的那个可能适用于大多数系统。
select analysis_date,ptf_id,stat_name,Bps,run_id
from rpt.rm_Report_History
where analysis_date > '20160102' and criteria_Set= 'Daily'
and ptf_id in( '10038','10039')
and report_section_group = 'Key_Risk_Figures'
and rm_rcp_param_name = 'Fund'
and stat_class = 'standaloneVaR'
and run_id = (SELECT max(run_id) FROM rpt.rm_Report_History WHERE
analysis_date > '20160102'
and criteria_Set= 'Daily'
and ptf_id in( '10038','10039')
and report_section_group = 'Key_Risk_Figures'
and rm_rcp_param_name = 'Fund'
and stat_class = 'standaloneVaR')
GROUP BY run_id
编辑:某些DBMS将要求您按所有选定的列进行分组:
...
GROUP BY analysis_date,ptf_id,stat_name,Bps,run_id
答案 1 :(得分:0)
我将假设tsql你的意思是SQL服务器......在这种情况下,抛出一个row_number() - 我最喜欢的SQL工具中的工具
select A1.*
from
(
select analysis_date,ptf_id,stat_name,Bps,run_id, row_number() over(partition by ptf_id order by run_id desc) as Run_Order
from rpt.rm_Report_History
where analysis_date > '20160102' and criteria_Set= 'Daily'
and ptf_id in( '10038','10039')
and report_section_group = 'Key_Risk_Figures'
and rm_rcp_param_name = 'Fund'
and stat_class = 'standaloneVaR' ) A1
where A1.Run_Order = 1
答案 2 :(得分:0)
这是使用cte的实现(适用于sql server 2008及更高版本)。
;with cte_1
as
(select analysis_date,ptf_id,stat_name,Bps,run_id,ROW_NUMBER() OVER(PARTITION BY ptf_id ORDER BY run_id desc) as RNO
from rpt.rm_Report_History
where analysis_date > '20160102' and criteria_Set= 'Daily'
and ptf_id in( '10038','10039')
and report_section_group = 'Key_Risk_Figures'
and rm_rcp_param_name = 'Fund'
and stat_class = 'standaloneVaR')
SELECT *
FROM cte_1
WHERE RNO=1