【问题标题】:SQL - Financial Year YTD CalcuationSQL - 财政年度年初至今计算
【发布时间】:2018-12-13 21:33:50
【问题描述】:

我正在尝试按日历年对查询进行分组来计算年初至今的总计,但有一列以从财政年度开始的分钟为单位计算总时间(即从同年的 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

你知道我怎样才能让它工作吗?

【问题讨论】:

  • 您使用的是哪个 dbms? (该代码是特定于产品的。)
  • @jarlh 我正在使用 SQL Server 2017
  • 样本数据和期望的结果真的很有帮助。

标签: sql sql-server parameters


【解决方案1】:

如果您想要累积总和,那么我希望:

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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    相关资源
    最近更新 更多