I am trying to calculate year to date totals grouping a query by calendar year but having a column which totals time in minutes from the beginning of the financial year (ie from 1st April of the same year the month occurred in if the month >= April otherwise 1st April from the previous year)
I have tried this with the following script but am unable to use a case statement in the sum() over() clause.
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
Do you know how I can get this to work?
If you want cumulative sums, then I would expect:
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;
If you want to do this for multiple years, then you need to extract the fiscal year. This is a little cumbersome, but doable:
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.