SQL中最大月/年的总和值

时间:2011-10-19 15:07:22

标签: sql-server

我有一个表(t_psg2_nav),其中包含相关列:fundnum,calcdate,return_active_daily,其中包含一组基金的有效回报时间序列。我想总结一下最近一个月的return_active_daily。我有以下但它什么也没有返回。不确定我是否在正确的轨道上,我该如何做到这一点?具体的编码会有所帮助,因为我对此很新:

SELECT      nav.fundnum AS 'Fund'
            ,sum(nav.return_active_daily) AS 'MTD Tracking'

FROM       t_psg2_nav nav

INNER JOIN  (SELECT fundnum
                    ,month(max(calcdate)) AS calcdate
                    ,return_active_daily
             FROM   t_psg2_nav
             GROUP BY fundnum, return_active_daily
             )
AS nav1 ON nav.fundnum = nav1.fundnum
AND nav.calcdate = nav1.calcdate

GROUP BY nav.fundnum

1 个答案:

答案 0 :(得分:1)

您的错误在子查询中; MONTH将返回表示月份的整数(即1-12)。当您使用语法(nav.calcdate = nav1.calcdate)加入时,没有等于“10”的日期。

请改为尝试:

SELECT  nav.fundnum AS 'Fund'
      , SUM(nav.return_active_daily) AS 'MTD Tracking'
FROM    t_psg2_nav nav
WHERE nav.calcdate >= DATEADD(MONTH, DATEDIFF(MONTH,0, SYSDATETIME()), 0)        
GROUP BY nav.fundnum 

假设你想要当前月份的回报率。