2016-09-29 55 views
0

我有一些不同的投資組合,每一種都有自己的ID,並與沿是一個run_id熱門ID對於每個記錄SQL

我所試圖做的是對每個日期的風險數量,拉這是與最大run_id每個組合

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' 

這給下面的輸出

output

+1

您可以放置​​所需的輸出嗎? –

+0

請標記RDMS .. –

回答

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 
0

我要去承擔的BPS數通過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 
1

這裏扔()--Literally我最喜歡的工具是用一個解決方案子選擇決定了最大首先在列表中選擇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 
+0

消息8120,級別16,狀態1,行1 列'rpt.rm_Report_History.analysis_date'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 – user2904400

+0

好吧,我猜你必須按所有選定的列進行分組。 –