代码之家  ›  专栏  ›  技术社区  ›  msinghm

SQL-财政年度YTD计算

  •  0
  • msinghm  · 技术社区  · 7 年前

    我试图计算按日历年分组的查询的年初至今总计,但有一列以分钟为单位计算从财政年度开始的时间(即从该月发生的同一年的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 回复  |  直到 7 年前
        1
  •  0
  •   Gordon Linoff    7 年前

    如果你想要累计金额,那么我希望:

    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;