Oracle PLSQL 中所有唯一记录的移动平均值

Moving average for all unique records in Oracle PLSQL

我有一个 table 结构如下

SQL> desc trx_mf_amfi_navs ;

Name                   Type          Nullable Default Comments 
---------------------- ------------- -------- ------- -------- 
SCHEME_CODE            NUMBER                                  
ISIN_DIV_PAYOUT_GROWTH VARCHAR2(100) Y                         
ISIN_DIV_REINVESTMENT  VARCHAR2(100) Y                         
SCHEME_NAME            VARCHAR2(200) Y                         
NET_ASSET_VALUE        NUMBER        Y                         
NAV_DATE               DATE    

                            

以下是不同共同基金计划的记录,仅显示了 2 个计划代码详细信息

我写了一个查询如下

Select t1.scheme_code,
       t1.scheme_name,
       t1.net_asset_value,
       round(avg(t1.net_asset_value)
             over(partition by t1.scheme_code order by t1.scheme_code
                  rows between 3 preceding and current row),
             4) as "3Day_SMA"
  from trx_mf_amfi_navs t1
 where t1.scheme_code in ('118834', '118825')
   and t1.nav_date >= '01-FEB-2022'

查询结果如下

我想要所有方案的输出,最后一个 nav_date 的移动平均数 scheme_code

Scheme_Code,Scheme_Name, NET_ASSET_VALUE,max(nav_date),3day_SMA

118825  Mirae Asset Large Cap Fund - Direct Plan - Growth   81.56   28-FEB-2022 81.1173
118834  Mirae Asset Emerging Bluechip Fund - Direct Plan - Growth   100.84  28-FEB-2022 99.7675

非常感谢您的帮助

如果我理解你是对的,你只是想将你现有的 table 和 3day_SMA 总结为 table,它只包含按 scheme_code 分组的最后一天的行。如果这就是您要找的,那么这应该可以解决您的问题:

 with
test1 as(
         Select t1.scheme_code,
                t1.scheme_name,
                t1.net_asset_value,
                t1.nav_date,
                round(avg(t1.net_asset_value)
                      over(partition by t1.scheme_code order by t1.scheme_code
                           rows between 3 preceding and current row),
                           4) as "3Day_SMA"
        from trx_mf_amfi_navs t1
        where t1.scheme_code in ('118834', '118825')
        and t1.nav_date >= '01-FEB-2022'
        )
        select * from test1 where (scheme_code,nav_date) in
        (select scheme_code,max(nav_date) from test1 group by scheme_code) 

或加入:

 Select t1.scheme_code,
        t1.scheme_name,
        t1.net_asset_value,
        t2.max_date,
        t1."3Day_SMA"
        from 
        (select scheme_code,scheme_name, net_asset_value,nav_date, round(avg(net_asset_value)
        over(partition by scheme_code order by scheme_code
        rows between 3 preceding and current row),4) as "3Day_SMA" from trx_mf_amfi_navs) t1,
        (select scheme_code,max(nav_date) max_date from trx_mf_amfi_navs group by scheme_code) t2
        where
        t1.scheme_code=t2.scheme_code
        and t1.scheme_code in ('118834', '118825')
        and t1.nav_date >= '01-FEB-2022'
        and t1.nav_date=t2.max_date