diff --git a/posthog/hogql_queries/insights/trends/query_builder.py b/posthog/hogql_queries/insights/trends/query_builder.py index 26c287600e455..7733bdfd41dcb 100644 --- a/posthog/hogql_queries/insights/trends/query_builder.py +++ b/posthog/hogql_queries/insights/trends/query_builder.py @@ -300,6 +300,34 @@ def _inner_select_query(self, inner_query: ast.SelectQuery | ast.SelectUnionQuer ), ) + if ( + self.query.trendsFilter is not None + and self.query.trendsFilter.smoothing_intervals is not None + and self.query.trendsFilter.smoothing_intervals > 1 + ): + rolling_average = ast.Alias( + alias="count", + expr=ast.Call( + name="floor", + args=[ + ast.WindowFunction( + name="avg", + args=[ast.Call(name="sum", args=[ast.Field(chain=["total"])])], + over_expr=ast.WindowExpr( + order_by=[ast.OrderExpr(expr=ast.Field(chain=["day_start"]), order="ASC")], + frame_method="ROWS", + frame_start=ast.WindowFrameExpr( + frame_type="PRECEDING", + frame_value=int(self.query.trendsFilter.smoothing_intervals - 1), + ), + frame_end=ast.WindowFrameExpr(frame_type="CURRENT ROW"), + ), + ) + ], + ), + ) + query.select = [rolling_average] + query.group_by = [] query.order_by = [] diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py index ec01ad63e7776..f22a9b4bd9724 100644 --- a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py +++ b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py @@ -1100,3 +1100,17 @@ def test_properties_filtering_with_materialized_columns_and_empty_string_as_prop ) assert response.results[0]["data"] == [1] + + def test_smoothing(self): + self._create_test_events() + + response = self._run_trends_query( + "2020-01-09", + "2020-01-20", + IntervalType.day, + [EventsNode(event="$pageview")], + TrendsFilter(smoothing_intervals=7), + None, + ) + + assert response.results[0]["data"] == [1, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0]