12个月的滚动数据

Rolling data for 12 month period

我想显示过去 12 个月,每个月都应该显示 12 个月前的总和。因此,2022 年 1 月显示 2021 年 1 月 -> 2022 年 1 月的总和,2022 年 2 月显示 2021 年 2 月 -> 2022 年 2 月的总和,依此类推。

My current data

Expected Result

我是 kusto 的新手,看来我需要使用 pivot 模式和 prev 功能,但是这几个月有点混乱。

如果您确定每个月都有数据,这就可以了。
如果不是,解决方案会变得有点复杂。

想法是创建一个累计金额列,然后将每个月的累计金额与上一年同月的此金额进行匹配。
它们之间的差值是最近 12 个月的总和。

// 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

另一种选择是遵循 window 描述的滑动聚合示例 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