财政年度的年初至今运行总额

时间:2016-08-11 07:18:48

标签: sql tsql business-intelligence

SELECT DISTINCT
    ACCOUNTDATE
    ,PROPERTYNAME
    ,rt.management
from aaa t
cross apply     
    (select SUM(MANAGEMENT) as management
     from aaa
     where 
     PROPERTYNAME = t.PROPERTYNAME and
     ACCOUNTDATE BETWEEN dateadd(MONTH, datediff(MONTH, 0,t.ACCOUNTDATE),0) -- start of month
AND t.ACCOUNTDATE 
    ) as rt
WHERE AccountDate BETWEEN @STARTOFMONTH_MAN AND @ENDOFMONTH_MAN
ORDER BY AccountDate

这是查找到目前为止的月份的查询。 如何从同一查询中查找会计年度的年初至今? 例如:从01/04 / 2015-31 / 03/2016的运行总计

2 个答案:

答案 0 :(得分:0)

不确定从哪个日期起你需要FY开始。假设来自@STARTOFMONTH_MAN。然后你可以得到FY开始

declare @fymonth int = 4; -- first month of FY.

declare @STARTOFMONTH_MAN date = '20160320';
select  fyStart = dateadd(MONTH,
                @fymonth - CASE WHEN month(@STARTOFMONTH_MAN) >= @fymonth THEN 1 ELSE 13 END,
                dateadd(YEAR, datediff(YEAR, 0, @STARTOFMONTH_MAN),0));

您可以通过创建日历表来简化这些日期计算。

修改
想法是使用较大的间隔和子区间的条件SUM数据来限制WHERE中的数据。

declare @fymonth int = 4; -- first month of FY.

SELECT DISTINCT
    ACCOUNTDATE
    ,PROPERTYNAME
    ,rt.FYManagement, rt.MonthManagement
FROM aaa t
CROSS APPLY     
    (SELECT 
        SUM(t2.MANAGEMENT) AS FYManagement
        ,SUM(CASE WHEN t2.ACCOUNTDATE BETWEEN 
                -- start of month for t.ACCOUNTDATE
            dateadd(MONTH, datediff(MONTH, 0, t3.ACCOUNTDATE), 0)
            AND t3.ACCOUNTDATE
         THEN t2.MANAGEMENT END) AS MonthManagement
     from aaa t2
     JOIN aaa t3 ON t3.primarykey = t.primarykey -- change as needed to get 1 to 1 JOIN
     where 
     t2.PROPERTYNAME = t.PROPERTYNAME and
     t2.ACCOUNTDATE BETWEEN 
                -- FY start for t.ACCOUNTDATE
                dateadd(MONTH,
                  @fymonth - CASE WHEN month(t.ACCOUNTDATE) >= @fymonth THEN 1 ELSE 13 END,
                  dateadd(YEAR, datediff(YEAR, 0, t.ACCOUNTDATE), 0));
                AND t.ACCOUNTDATE 
    ) as rt
WHERE AccountDate BETWEEN @STARTOFMONTH_MAN AND @ENDOFMONTH_MAN
ORDER BY AccountDate

答案 1 :(得分:0)

声明@fymonth int = 4; - 财年第一个月。

SELECT DISTINCT     ACCOUNTDATE     ,PROPERTYNAME     ,rt.FYManagement,rt.MonthManagement 从aaa t 交叉申请
    (选择         SUM(t2.MANAGEMENT)作为风险管理         ,SUM(在t2.ACCOUNTDATE之间的情况                  - t.ACCOUNTDATE的月份开始             dateadd(MONTH,datediff(MONTH,0,t3.ACCOUNTDATE),0)             和t3.ACCOUNTDATE          那么t2.MANAGEMENT END)作为MonthManagement      来自aaa t2      JOIN aaa t3 ON t3.primarykey = t.primarykey - 根据需要更改为1到1加入      哪里      t2.PROPERTYNAME = t.PROPERTYNAME和      t2.ACCOUNTDATE之间                  - 为t.ACCOUNTDATE开始                 DATEADD(月,                   @fymonth - CASE WHEN月(t.ACCOUNTDATE)> = @fymonth那么1节13结束,                   dateadd(YEAR,datediff(YEAR,0,t.ACCOUNTDATE),0));                 和t.ACCOUNTDATE     )rt 在@STARTOFMONTH_MAN和@ENDOFMONTH_MAN之间的帐户日期 按帐户日期订购