SQL-财政年度年初至今的计算

时间:2018-07-05 11:52:14

标签: sql sql-server parameters

我正在尝试按日历年对查询进行分组,以计算年初至今的总计,但是该列具有从财务年度开始(即从同年的4月1日开始,以分钟为单位)的时间总计(以分钟为单位) > = 4月,否则为上一年的4月1日)

我已经使用以下脚本尝试过此操作,但是无法在sum()over()子句中使用case语句。

    declare @yearmonth int = 4
declare @NumPreceeding int = case when right(@yearmonth,2) in (01,02,03) then 9+right(@yearmonth,1) 
                                                                                    else (((12-(right(@yearmonth,2)+8)))*(-1)) 
                                                                                                                    end
select  ColumnDescription
       ,sum(TotalMinutes) [TotalMinutes]
          ,sum(sum(TotalMinutes)) over (order by YearMonth rows between cast(@NumPreceeding as int) preceding and current row)
          ,YearMonth
from MyTable
where yearmonth between '201704' and '201706'
group by ColumnDescription ,YearMonth
order by yearmonth

您知道我该如何使用它吗?

1 个答案:

答案 0 :(得分:0)

如果您想要累计金额,那么我期望:

select ColumnDescription, YearMonth, sum(TotalMinutes) as TotalMinutes,
       sum(sum(TotalMinutes)) over (partition by ColumnDescription order by YearMonth) as running_TotalMinutes
from MyTable
where yearmonth between '201704' and '201706'
group by ColumnDescription, YearMonth
order by yearmonth;

如果要执行此操作多年,则需要提取会计年度。这有点麻烦,但是可行:

select ColumnDescription, YearMonth, sum(TotalMinutes) as TotalMinutes,
       sum(sum(TotalMinutes)) over (partition by ColumnDescription, v.fiscal_year order by YearMonth) as running_TotalMinutes
from MyTable t cross apply
     (values (case when right(yearmonth, 2) >= '04' then cast(left(yearmonth, 4) as int)
                   else cast(left(yearmonth, 4) as int) - 1
              end)
     ) v(fiscal_year)
group by ColumnDescription, YearMonth
order by yearmonth;