Rolling data for 12 month period

Viewed 148

I wanna show the last 12 months, and each of those months should show the sum of 12 months back. So January 2022 shows sum of January 2021 -> January 2022, February 2022 shows sum of February 2021 -> February 2022 and so on.

My current data

Expected Result

I new in kusto, seems i need use pivot mode with prev function but these month period a bit confusing.

2 Answers

If you know for sure that you have data for each month, this will do the trick.
If not, the solution will get a bit more complicated.

The Idea is to create an accumulated sum column and then match each month accumulated sum with this of the same month from the previous year.
The difference between them is the sum of the last 12 months.

// Data sample generation. Not part of the solution.
let t = materialize(range i from 1 to 10000 step 1 | extend dt = ago(365d*5*rand()) | summarize val = count() by year = getyear(dt), month = getmonth(dt));
// Solution starts here.
t
| order by year asc, month asc
| extend cumsum_val = row_cumsum(val) - val, prev_year = year - 1
| as t2
| join kind=inner t2 on $left.prev_year == $right.year and $left.month == $right.month
| project year, month = format_datetime(make_datetime(year,month,1),'MM') , last_12_cumsum_val = cumsum_val - cumsum_val1
| evaluate pivot(month, any(last_12_cumsum_val), year)
| order by year asc
year 01 02 03 04 05 06 07 08 09 10 11 12
2018 1901 2020 2018 2023 2032 2039 2015 2025 2039
2019 2045 2048 2029 2043 2053 2040 2041 2027 2025 2037 2050 2042
2020 2035 2016 2024 2022 1999 2009 1989 1996 1975 1968 1939 1926
2021 1926 1931 1936 1933 1945 1942 1972 1969 1981 2007 2020 2049
2022 2051 2032 2019 2002

Fiddle

Another option is to follow the sliding window aggregations sample described here:

let t = materialize(range i from 1 to 10000 step 1 | extend dt = ago(365d*5*rand()) | summarize val = count() by year = getyear(dt), month = getmonth(dt) | extend Date = make_datetime(year, month, 1));
let window_months = 12;
t
| extend _bin = startofmonth(Date)
| extend _range = range(1, window_months, 1)
| mv-expand _range to typeof(long)
| extend end_bin = datetime_add("month", _range, Date)
| extend end_month = format_datetime(end_bin, "MM"), end_year = datetime_part("year", end_bin)
| summarize sum(val), count() by end_year, end_month
| where count_ == 12
| evaluate pivot(end_month, take_any(sum_val), end_year)
| order by end_year asc
end_year 01 02 03 04 05 06 07 08 09 10 11 12
2018 1921 2061 2036 2037 2075 2067 2038 2025 2029
2019 2012 2006 2015 2022 1997 2015 2012 2010 1994 2002 2029 2035
2020 2012 2002 1967 1949 1950 1963 1966 1976 1982 2016 1988 1972
2021 1990 1987 1991 1996 2026 2004 2005 1996 1991 1966 1989 1993
2022 1979 1983 1981 1977 1931
Related