From 0ae0364497cd203005e681d223d990e608af61fb Mon Sep 17 00:00:00 2001 From: Tom Owers Date: Fri, 5 Jan 2024 16:51:01 +0000 Subject: [PATCH] feat(trends): Added smoothing to new trends query runner (#19578) * Added smoothing to new trends query runner * Update query snapshots * Update query snapshots * Fixed tests * Update query snapshots * Updated the name to rolling average * Fixed snaoshots * Update query snapshots --------- Co-authored-by: github-actions <41898282+github-actions[bot]@users.noreply.github.com> --- .../insights/trends/query_builder.py | 28 +++++++++++++++++++ .../trends/test/test_trends_query_runner.py | 14 ++++++++++ 2 files changed, 42 insertions(+) diff --git a/posthog/hogql_queries/insights/trends/query_builder.py b/posthog/hogql_queries/insights/trends/query_builder.py index 26c287600e4553..7733bdfd41dcb6 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 a8e966d3ccbb0a..b54d4ca1470153 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 @@ -1144,3 +1144,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]