Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(bi): compare worksheet results across periods (#112127)

Marius Andraab6526a370fc
diff --git a/docs/published/handbook/engineering/data-warehouse.md b/docs/published/handbook/engineering/data-warehouse.md
index 649804bcf83d..6a4675f0ab91 100644
--- a/docs/published/handbook/engineering/data-warehouse.md
+++ b/docs/published/handbook/engineering/data-warehouse.md
@@ -38,6 +38,10 @@ Older saves containing only SQL still open in the SQL editor. Their original she
The worksheet date picker supports rolling windows, fixed ranges, this/last month and quarter, and year to date. **Date** selects the column that receives dashboard date ranges; **No date column** explicitly opts out. A dashboard range replaces the worksheet range. Dashboard property filters combine with worksheet conditions. Event-based tables retain standard PostHog property filtering with any date-column selection, using `{filters.native(date_expression)}` or `{filters.native(null)}` when overriding the default date column. Other tables bind dashboard property keys to worksheet fields, including the property key in a field such as `properties.plan`. Unmapped or ambiguous property keys produce a query error instead of silently applying the wrong filter. Reopen and save older BI worksheets to update their generated SQL with dashboard-aware placeholders.
+The comparison picker adds the previous period or a custom offset, including one year earlier. Tables, bar, line, and area charts support comparisons with up to two dimensions. Previous-period dates align to the current axis, and the legend identifies each period. Both periods use the effective dashboard date range and property filters. Comparisons require a bounded range and turn off when the worksheet switches to all time or an unsupported chart.
+
+Generated comparison queries use `{filters.previous}` (or its column-bound form) for the comparison range and `{filters.compareDate(expr)}` to align date dimensions. Custom native date columns use `{filters.previous.native(expr)}`. Month, quarter, and year dimensions pass their bucket as a second argument to `compareDate`, so month lengths and leap years do not move points into the wrong bucket. `HogQLFilters.compareFilter` supplies the comparison offset; missing offsets use the previous period.
+
Use the table picker in the data pane to browse PostHog, warehouse, view, and system tables, with direct-connection tables grouped by schema.
The selected table is highlighted; expanding a folder does not select it.
Direct connections group tables by schema. Search matches table and folder names without changing the sidebar search.
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index 98ea983dc5e4..035fbe0da3a8 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -1757,9 +1757,9 @@ snapshots:
components-mcp-use-case-card--surveys-create--light:
hash: v1.k794b7964.2ce59a009bfce14f01a88f688627cf4b1def20c28ce5124288a54f9c62ffd3a6.wIhKopBY00iVCPnC9GB4QncFt-dCm8Gq9Uz6FYXBZ68
components-message-tool-calls-editor--editable-tool-calls--dark:
- hash: v1.k794b7964.7adaad1e91b71d0b933afe541a20fd43112e39d56d6638abadfae6a830bb0c15.TxnbKwXIG1XbB5e4KpRJa4-PA-wl-kKOWbtX1ERVqLU
+ hash: v1.k794b7964.bf5d7e9a07a313eb905517ad07b3b9be0b7efe64532efc72fa97a824aa75a320.E85JvFQYNnizHUgjnQ9GPVwmu_6NIXmyHetF0eKWR70
components-message-tool-calls-editor--editable-tool-calls--light:
- hash: v1.k794b7964.4a10839159f5b3f989112539bb2a720f04460890fae5914a3516457e7cba92f3.Snir6e_iAMVVl1tdItfy70BRcAHw5Zem9Kk0ujjMQIo
+ hash: v1.k794b7964.e23addac27e56509f0caed349da836f0963b87500639d1097f948a5eff9942ec.DaRlPJVS3Kckngsx8aJC0uoIJYOHBm2xQh__x5rXYoY
components-navpanelproductpush--all-products--dark:
hash: v1.k794b7964.d6cc4da0e30950f4e3bf7338d86856529e48c45785bae5a85ccf4fd3ed7c3ad0.8n61Z9x6l3I3qfdAzk46yr7fAFHoYNdo3tjEKyJlcIo
components-navpanelproductpush--all-products--light:
@@ -9571,37 +9571,37 @@ snapshots:
scenes-app-data-warehouse-settings-schemas--multi-schema--light:
hash: v1.k794b7964.e5d678194a8e191fdf4f8a92cd7328f1e3cb162a81d3c4d05ef608f3c61537da.ZshlecoDn8CpsaVHaONi7UiXq8r-Xi4zJSWKeg7nAP0
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--dark:
- hash: v1.k794b7964.d974890788e1b5c6e0612f1414c1fddf0bd17b5cd1946e059b75e5c67626b265.ZdKUpc_7P063x9hsZsEv5oyBQ0pTWlQkbyj3NxHajn4
+ hash: v1.k794b7964.41aa02c0a9c57f31d8b4dceb3d559064a6ac666de24a627146be0ef8ca2580bb.KueO1kPhMkYNn4NBYptydJ4Dw44kbfIm6gCbcIibn2E
scenes-app-data-warehouse-sql-editor--bi-calculated-measure-editor--light:
- hash: v1.k794b7964.59b4431c1c66fbeccdb380fbe3061b503b165b885858360e4c717cf2aed9f45d._6s9YXfYDH3I0OYh0On74OprQckRDkXCnbGJk6dVaac
+ hash: v1.k794b7964.b5192f0e2350e306e6d0cc8766b43d244c9fe91eeee999e1fb97e5685dcb398a.9UQD4sOiiPThMGhxjJNZzN1ZgEmP_TBTXo0Aj-91WPY
scenes-app-data-warehouse-sql-editor--bi-connections--dark:
- hash: v1.k794b7964.21db0db416dae779e29a200bf20098835b6697820e9c8c8f83a83431fd6aa6c3.eOVi8lx-ptmIAwLjW2luhAXdHaDTXKE-BRgqiRCwRoE
+ hash: v1.k794b7964.97fdb4104142664ae02367e14153e70761f2e85d3b4a78be17df7eb467dfb7ac.5mHIvQIi81vR2UfkryG5TPNfYLbgBAIeTSmMQhcZddE
scenes-app-data-warehouse-sql-editor--bi-connections--light:
- hash: v1.k794b7964.f783145262bef5849937151f085f59cda0f60ebb20fd0fa601d318b529e1d6c6.Hj-7-UypjU2RfkegVlJFUUpRLQUKOp415WXJKsIFDaI
+ hash: v1.k794b7964.28bb2ee95b0f7344ca83f107acbc3176ef8b41bb9050abe985491c07c893a935.XoOu_8bCWvLbH1pHDCjoftd2VAO3jANSIAqtwSfryu0
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--dark:
- hash: v1.k794b7964.bc68d1229339cd021301f8ef8275693a0e2c045dcb3ac740bcfb27eb26cb9459.M7j-horfW3uRUW53GS2dGKkHMQGgTegra-XAedoP2jM
+ hash: v1.k794b7964.9846e12af7620a533cf6dded790e7edbd1746a8ea3688ecb7a241a05a98e48b5.RWb13JOOPQRGzSh0jzLOfma_0I7IXg6a7uZGuQCo-MA
scenes-app-data-warehouse-sql-editor--bi-data-source-picker--light:
- hash: v1.k794b7964.6cd25146afa877d1c17afdc2cc39295b04877fec5c051fab1364717a2591b05a.iDScPI6Bq4P-WW4g3GKaW1GTOFpWn4gSWO37rpr_nSk
+ hash: v1.k794b7964.8eff07d5b039193316e4c2c88fd76261eb402a9d59501f668cb597e9c5115723.wmVx36EMRisW55v9o_8aEe1qwJh7EDvTSvY7dZWD5Tg
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--dark:
- hash: v1.k794b7964.c595896d97450a63a8cfda5d6024a4f117a781e675908f371a995be4f040210d.8QX_6pcXJ2Tg65hLue1pj8EH0UcwHB1J_O6BBpUtBoQ
+ hash: v1.k794b7964.50b4f288a3727642242c890e7e1a68e435ac47144545dda5b336b252ff95f164.HQC_z08nDoAjGFRajKf5aEde2BhWM8zwsHJkoPXuO9A
scenes-app-data-warehouse-sql-editor--bi-edit-saved-insight--light:
- hash: v1.k794b7964.e72c20769ccdee6ab14529fef33535278c318366ce821f0832189fb6c5d12cc6.k7AA7bl7-ccEd4ffRYLfJvNSlhHUo5IVNjLi2ENsmz0
+ hash: v1.k794b7964.e4d047ec1ab8a5cdaa994a5c318b11de7320a8ce68f3a39a8c4880a3b9e77baa.07Y3AFU8UBvpaQvPxHifLqp0_Ic2aksX0h5bST9bW4Y
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--dark:
- hash: v1.k794b7964.e96e5bd64e5c355152d4f91ae58100f74aaf16f50c4dc6b65fe01282ce454dad.xY9LiVJ2cUp5i0jqV7OvXGOf83E2dw0qTS9d3CzgOiY
+ hash: v1.k794b7964.a396976c1ac19d1018d181cb7a1a45b9094c1afae27b09ce5c47370dbd32719e.8W7iOXmHeV_jCUjH5EIjAg3Le0HCj-m8Uf0zVxal0ic
scenes-app-data-warehouse-sql-editor--bi-empty-worksheet--light:
- hash: v1.k794b7964.81e44e31cf9a3a66cf699ee4aaa6d15ff981d48e2f4d63289275f83689a61102.3Sb3cTvLqoLdO5Basj36wcg6jbUjGyVWuLTq1J5zc8k
+ hash: v1.k794b7964.5b94e2bde6e76fca16d810c564720fbaee3d25678eff894cb660766da8f86a0b.sPgfzc_N0i2i0a80EUTnLmvKajKY4Y5V8QKI_6R0PdE
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--dark:
- hash: v1.k794b7964.7aa3ce1ca0ddbf4cc88ca87fe9f538a2e309a0eac8ce40317b696a503e5c9886.gY_yAskTW8CBQWsR6bvyOBzxPdTTiyd79RHV3WMyLdk
+ hash: v1.k794b7964.ba41360a7ee0745e949e852af5672dd01da71c97ea05e1451d06c1c46cc7fd8b.C0-r7WaPwx_f3I-C4gOxHm5K6E9NX4AyiCiKkzrbWQk
scenes-app-data-warehouse-sql-editor--bi-mode-worksheet--light:
- hash: v1.k794b7964.7bc4acb07b01c453c74b160c6a90548ec9b6d708c559c5d70843875de5722df9.uiBpmyXUGsXgUWZS2r1V-dKddo5DAUe51vAGNEbxxo8
+ hash: v1.k794b7964.7dadf5e05828984738b4d4e381409086432b4c5c748bcc839b1da6f0b19fa2d4.KvqPBipW63BCUPdnl8dSa_TDBkWrXMDG6cLVV0UKpp8
scenes-app-data-warehouse-sql-editor--bi-quick-filters--dark:
- hash: v1.k794b7964.833eae8ac76fa742aecd5194c3b81df2f47d922b010ac3b01dc2eb03715c6e33.qJSwQsYj-E5tK1oqe2-qLTHN3lJ6gfsnLvq73-MBTWc
+ hash: v1.k794b7964.05b26029903e019a4583d294019df0b1ec89d36a072008e2b9e8ab5212641916.ak6MRXP4V4bx5U7jk8tE_gdLLMGCbdfuch4rdGnVGM8
scenes-app-data-warehouse-sql-editor--bi-quick-filters--light:
- hash: v1.k794b7964.1b55ff7f599387807ca9aff238dd8d2cc8ed784aa5fb8beb47ea31ba8b96fb2b.T_EBsBIz2CPpYaKfoYjmDET7rVsOkbHJMdVeNiMEjcA
+ hash: v1.k794b7964.a4d55c43984207e6b9d84ee4d76b63a8c18b2cf5ab1b1c00a31baf3c1cdea3fa.wjy1v69m4-V9bhC-7ZgCJB7nZoI98tyDErHNxCOAhH8
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--dark:
- hash: v1.k794b7964.514a7dd8548054e3ba3509d30ea03050436ebda1778783ccea276a58796862bb.PIbqNZ6ihv-wOghiSKsPFBS2InXBWbZsN955dGwCRjQ
+ hash: v1.k794b7964.24935f4243bb998e0429c168b387b500710ba25ef0b13b3a5b1ebbd97af3a0d1.IJ8Gx6rj4Ppt8cLxoKy0KKn6nSqiCBA4teFv30sUKPk
scenes-app-data-warehouse-sql-editor--bi-quick-filters-narrow--light:
- hash: v1.k794b7964.c616d9350a2e4dea4d69e032dc22f2f359d02944e5cef25564e1946946c665e6.cBr928anc4KbDbb3yI6SoeT6vgCwqIOLBpEYE3Zne1I
+ hash: v1.k794b7964.458ee997d5f498390280ce9bc13edf52f4e2a8dbb7653e93f640487530f831da.Lu561UQbXNtDoJcg99jjZe8L-cf49MH1Ni9cY0ERg2w
scenes-app-data-warehouse-sql-editor--bi-saved-insight--dark:
hash: v1.k794b7964.24b439b90164ae7db044155845ca7672d56a4cba3114d585495e5dda13f24767.wjZpVrMTZpKpD3Ih75kZd7Q0gbrlPNB-GP22OYGTzZE
scenes-app-data-warehouse-sql-editor--bi-saved-insight--light:
diff --git a/frontend/src/queries/schema.json b/frontend/src/queries/schema.json
index 38b381f47fdd..2c953570b714 100644
--- a/frontend/src/queries/schema.json
+++ b/frontend/src/queries/schema.json
@@ -6155,6 +6155,9 @@
},
"type": "array"
},
+ "compareFilter": {
+ "$ref": "#/definitions/CompareFilter"
+ },
"dateField": {
"anyOf": [
{
@@ -29387,6 +29390,10 @@
"$ref": "#/definitions/BreakdownFilter",
"description": "Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown."
},
+ "compareFilter": {
+ "$ref": "#/definitions/CompareFilter",
+ "description": "Comparison range consumed by {filters.previous} and {filters.compareDate(expr)}."
+ },
"dateRange": {
"$ref": "#/definitions/DateRange"
},
diff --git a/frontend/src/queries/schema/schema-business-intelligence.ts b/frontend/src/queries/schema/schema-business-intelligence.ts
index 7b457077d993..1e6b09170f7a 100644
--- a/frontend/src/queries/schema/schema-business-intelligence.ts
+++ b/frontend/src/queries/schema/schema-business-intelligence.ts
@@ -2,6 +2,7 @@ import { ChartDisplayType } from '~/types'
import {
ChartSettings,
+ CompareFilter,
DatabaseSerializedFieldType,
DateRange,
HogQLQuery,
@@ -82,6 +83,7 @@ export interface BIConfig {
/** Column that receives the worksheet and dashboard date range. */
dateField?: BIField | null
dateRange?: DateRange
+ compareFilter?: CompareFilter
chartType: ChartDisplayType
rows: BIField[]
columns: BIField[]
diff --git a/frontend/src/queries/schema/schema-general.ts b/frontend/src/queries/schema/schema-general.ts
index 5ce256deb9d2..142e14303716 100644
--- a/frontend/src/queries/schema/schema-general.ts
+++ b/frontend/src/queries/schema/schema-general.ts
@@ -698,6 +698,8 @@ export type CachedHogQLQueryResponse = CachedQueryResponse<HogQLQueryResponse>
export interface HogQLFilters {
properties?: AnyPropertyFilter[]
dateRange?: DateRange
+ /** Comparison range consumed by {filters.previous} and {filters.compareDate(expr)}. */
+ compareFilter?: CompareFilter
filterTestAccounts?: boolean
/** Time granularity consumed by the {filters.interval} placeholder. Set from the dashboard-level interval. */
interval?: IntervalType
diff --git a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
index c262cd1b214d..0ccc0176a071 100644
--- a/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
+++ b/frontend/src/scenes/data-warehouse/editor/SQLEditorScene.stories.tsx
@@ -429,11 +429,12 @@ export const BIEmptyWorksheet: Story = {
...BIModeWorksheet,
parameters: {
...BIModeWorksheet.parameters,
+ // An explicit empty query prevents restoring another story's persisted worksheet.
pageUrl: `${urls.businessIntelligence()}#q=`,
testOptions: { waitForSelector: '[data-attr="bi-editor-data-source"]' },
},
play: async ({ canvasElement }) => {
- await within(canvasElement).findByText('Select a table to list its fields.')
+ await expect(within(canvasElement).findByText('Select a table to list its fields.')).resolves.toBeVisible()
},
}
diff --git a/posthog/hogql/filters.py b/posthog/hogql/filters.py
index 377009e1a86b..e57c84f525ae 100644
--- a/posthog/hogql/filters.py
+++ b/posthog/hogql/filters.py
@@ -1,6 +1,6 @@
import re
import dataclasses
-from datetime import datetime
+from datetime import datetime, timedelta
from typing import Any, Optional, TypeVar, cast
from dateutil.parser import isoparse
@@ -8,6 +8,7 @@ from dateutil.parser import isoparse
from posthog.schema import (
BreakdownFilter,
BreakdownType,
+ DateRange,
EmptyPropertyFilter,
HogQLFilters,
IntervalType,
@@ -31,6 +32,8 @@ from posthog.hogql.errors import QueryError
from posthog.hogql.property import bound_property_to_expr, property_to_expr
from posthog.hogql.visitor import CloningVisitor, clone_expr
+from posthog.hogql_queries.utils.query_compare_to_date_range import QueryCompareToDateRange
+from posthog.hogql_queries.utils.query_previous_period_date_range import QueryPreviousPeriodDateRange
from posthog.models import Property, Team
from posthog.utils import relative_date_parse_with_delta_mapping
@@ -222,6 +225,8 @@ class ReplaceFilters(CloningVisitor):
return node
def visit_placeholder(self, node):
+ if node.chain == ["filters", "previous"]:
+ return self._comparison_visitor().visit_placeholder(ast.Placeholder(expr=ast.Field(chain=["filters"])))
# The column-bound form {filters(expr AS key, ...)}: the query author maps each filter key
# onto an expression of their own query, so the table restrictions of plain {filters} don't
# apply. A Call never has a chain, so the chain-based branches below can't match it.
@@ -232,10 +237,16 @@ class ReplaceFilters(CloningVisitor):
# {filters.breakdown(expr AS key, ...)} substitutes the column bound to the selected breakdown.
if isinstance(node.expr, ast.ExprCall) and isinstance(node.expr.expr, ast.Field):
call_chain = node.expr.expr.chain
- if call_chain == ["filters", "native"]:
+ if call_chain in (["filters", "native"], ["filters", "previous", "native"]):
if len(node.expr.args) != 1:
raise QueryError("{filters.native(expr)} requires one date expression or null.")
- return self._replace_native_filters(node.expr.args[0])
+ visitor = self._comparison_visitor() if "previous" in call_chain else self
+ return visitor._replace_native_filters(node.expr.args[0])
+
+ if call_chain == ["filters", "previous"]:
+ return self._comparison_visitor()._replace_bound_filters(ast.Call(name="filters", args=node.expr.args))
+ if call_chain == ["filters", "compareDate"]:
+ return self._replace_comparison_date(node.expr.args)
if call_chain == ["filters", "interval"]:
return self._replace_interval(node.expr.args)
if call_chain == ["filters", "breakdown"]:
@@ -394,6 +405,79 @@ class ReplaceFilters(CloningVisitor):
return exprs[0]
return ast.And(exprs=exprs)
+ def _replace_comparison_date(self, args: list[ast.Expr]) -> ast.Expr:
+ if len(args) not in (1, 2):
+ raise QueryError(
+ "{filters.compareDate(expr, bucket)} requires a date expression and optional calendar bucket."
+ )
+ bucket = None
+ if len(args) == 2:
+ if not isinstance(args[1], ast.Constant) or args[1].value not in ("month", "quarter", "year"):
+ raise QueryError("The comparison bucket must be 'month', 'quarter', or 'year'.")
+ bucket = args[1].value
+ previous = self._comparison_visitor()._resolve_date_from()
+ current = self._resolve_date_from()
+ assert previous is not None and current is not None
+ if bucket is not None:
+ width = {"month": 1, "quarter": 3, "year": 12}[bucket]
+ current_bucket = (current.year * 12 + current.month - 1) // width
+ previous_bucket = (previous.year * 12 + previous.month - 1) // width
+ return ast.Call(
+ name="addMonths",
+ args=[self.visit(args[0]), ast.Constant(value=(current_bucket - previous_bucket) * width)],
+ )
+ midnight = all(date.hour == date.minute == date.second == date.microsecond == 0 for date in (current, previous))
+ return ast.Call(
+ name="addDays" if midnight else "addSeconds",
+ args=[
+ self.visit(args[0]),
+ ast.Constant(
+ value=(current.date() - previous.date()).days
+ if midnight
+ else int((current - previous).total_seconds())
+ ),
+ ],
+ )
+
+ def _comparison_visitor(self) -> "ReplaceFilters":
+ if not self.filters or not self.filters.dateRange or self.filters.dateRange.date_from in (None, "all"):
+ raise QueryError(
+ "Period comparisons require a bounded date range. Choose a start date instead of all time."
+ )
+ compare_to = self.filters.compareFilter.compare_to if self.filters.compareFilter else None
+ date_range = self.filters.dateRange
+ _, delta_mapping = self._parse_date_from()
+ exact = bool(date_range.explicitDate or delta_mapping is None or SUB_DAY_DELTA_KEYS & delta_mapping.keys())
+ interval = IntervalType.MINUTE if exact else IntervalType.DAY
+ if exact:
+ start = self._resolve_date_from()
+ end, inclusive = self._resolve_date_to()
+ assert start is not None
+ end = end or self._current_time()
+ date_range = DateRange(
+ date_from=start.isoformat(),
+ date_to=(end + timedelta(microseconds=1) if inclusive else end).isoformat(),
+ explicitDate=True,
+ )
+ comparison = (
+ QueryCompareToDateRange(date_range, self.team, interval, self._current_time(), compare_to=compare_to)
+ if compare_to
+ else QueryPreviousPeriodDateRange(date_range, self.team, interval, self._current_time())
+ )
+ previous_filters = self.filters.model_copy(
+ update={
+ "dateRange": DateRange(
+ date_from=comparison.date_from().isoformat(),
+ date_to=(comparison.date_to() + (timedelta() if exact else timedelta(microseconds=1))).isoformat(),
+ explicitDate=True,
+ )
+ }
+ )
+ visitor = ReplaceFilters(previous_filters, self.team, self.database)
+ visitor._now = self._current_time()
+ visitor.selects = self.selects
+ return visitor
+
def _replace_bound_filters(self, call: ast.Call) -> ast.Expr:
# Parse bindings before the no-filters early return, so malformed usage surfaces in the
# SQL editor even while no filter is set yet.
diff --git a/posthog/hogql/placeholders.py b/posthog/hogql/placeholders.py
index 211b8ad13b8a..1b3ad9fb0a16 100644
--- a/posthog/hogql/placeholders.py
+++ b/posthog/hogql/placeholders.py
@@ -62,6 +62,12 @@ class FindPlaceholders(TraversingVisitor):
# Dotted call forms like {filters.interval('week')} and {filters.breakdown(...)} are
# resolved by replace_filters too.
self.has_filters = True
+ if node.expr.expr.chain in (
+ ["filters", "previous"],
+ ["filters", "native"],
+ ["filters", "previous", "native"],
+ ):
+ self.has_date_filters = True
else:
self.placeholder_expressions.append(node.expr)
diff --git a/posthog/hogql/test/test_filters.py b/posthog/hogql/test/test_filters.py
index 3cdb1fed8372..ea7e72d081e2 100644
--- a/posthog/hogql/test/test_filters.py
+++ b/posthog/hogql/test/test_filters.py
@@ -9,6 +9,7 @@ from posthog.schema import (
Breakdown,
BreakdownFilter,
CohortPropertyFilter,
+ CompareFilter,
DateRange,
ElementPropertyFilter,
EventMetadataPropertyFilter,
@@ -28,6 +29,7 @@ from posthog.hogql.errors import QueryError
from posthog.hogql.filters import replace_filters
from posthog.hogql.parser import parse_expr, parse_select
from posthog.hogql.printer import prepare_and_print_ast
+from posthog.hogql.query import execute_hogql_query
from posthog.hogql.visitor import clear_locations
from products.cohorts.backend.models.cohort import Cohort
@@ -49,6 +51,84 @@ class TestFilters(BaseTest):
context=HogQLContext(team_id=self.team.pk, enable_select_queries=True),
)[0]
+ @parameterized.expand(
+ [
+ ("native_previous", "{filters.previous}", None, "2020-01-01", 31),
+ ("custom_native_previous", "{filters.previous.native(timestamp)}", None, "2020-01-01", 31),
+ (
+ "bound_previous",
+ "{filters.previous(timestamp AS timestamp, properties.plan AS 'plan')}",
+ None,
+ "2020-01-01",
+ 31,
+ ),
+ ("previous_year", "{filters.previous}", "-1y", "2019-02-01", 365),
+ ]
+ )
+ @time_machine.travel("2020-02-15T12:00:00Z", tick=False)
+ def test_comparison_filters(
+ self, _name: str, placeholder: str, compare_to: str | None, previous_start: str, days: int
+ ) -> None:
+ filters = HogQLFilters(
+ dateRange=DateRange(date_from="mStart"),
+ compareFilter=CompareFilter(compare=True, compare_to=compare_to),
+ properties=[EventPropertyFilter(key="plan", value="pro", operator="exact")],
+ )
+ query = self._parse_select("SELECT {filters.compareDate(timestamp)} FROM events WHERE " + placeholder)
+ sql = self._print_ast(replace_filters(query, filters, self.team))
+ self.assertIn(f"addDays(timestamp, {days})", sql)
+ self.assertIn(previous_start, sql)
+ self.assertIn("properties.plan", sql)
+ self.assertIn("'pro'", sql)
+ self.assertNotIn("{filters", sql)
+ assert filters.dateRange is not None
+ self.assertEqual(filters.dateRange.date_from, "mStart")
+
+ @parameterized.expand(
+ [
+ ("leap_february", "2020-02-15", "mStart", None, "month", "2020-01-30", "2020-02-01"),
+ ("february", "2021-02-15", "mStart", None, "month", "2021-01-31", "2021-02-01"),
+ ("quarter", "2020-05-15", "qStart", None, "quarter", "2020-01-31", "2020-04-01"),
+ ("year", "2021-05-15", "yStart", "-1y", "year", "2020-02-29", "2021-01-01"),
+ ]
+ )
+ def test_calendar_comparison_buckets(
+ self, _name: str, now: str, date_from: str, compare_to: str | None, bucket: str, previous: str, expected: str
+ ) -> None:
+ filters = HogQLFilters(
+ dateRange=DateRange(date_from=date_from), compareFilter=CompareFilter(compare=True, compare_to=compare_to)
+ )
+ date = ast.Placeholder(
+ expr=ast.ExprCall(
+ expr=ast.Field(chain=["filters", "compareDate"]),
+ args=[ast.Call(name="toDateTime", args=[ast.Constant(value=previous)]), ast.Constant(value=bucket)],
+ )
+ )
+ query = self._parse_select(
+ "SELECT toString(toDate(dateTrunc({bucket}, {date})))",
+ placeholders={"bucket": ast.Constant(value=bucket), "date": date},
+ )
+ with time_machine.travel(now, tick=False):
+ query = replace_filters(query, filters, self.team)
+ result = execute_hogql_query(query, team=self.team)
+ assert result.results == [(expected,)]
+
+ def test_comparison_rejects_unbounded_dates(self) -> None:
+ with self.assertRaisesMessage(QueryError, "Period comparisons require a bounded date range"):
+ replace_filters(
+ self._parse_select("SELECT count() FROM events WHERE {filters.previous}"),
+ HogQLFilters(dateRange=DateRange(date_from="all")),
+ self.team,
+ )
+
+ @time_machine.travel("2020-02-15T12:00:00Z", tick=False)
+ def test_comparison_preserves_subday_boundaries(self) -> None:
+ query = self._parse_select("SELECT {filters.compareDate(timestamp)} FROM events WHERE {filters.previous}")
+ sql = self._print_ast(replace_filters(query, HogQLFilters(dateRange=DateRange(date_from="-1h")), self.team))
+ self.assertIn("addSeconds(timestamp, 3600)", sql)
+ self.assertIn("less(timestamp, toDateTime('2020-02-15 11:00:00.000000'))", sql)
+ self.assertIn("greaterOrEquals(timestamp, toDateTime('2020-02-15 10:00:00.000000'))", sql)
+
def test_replace_filters_empty(self):
select = replace_filters(self._parse_select("SELECT event FROM events"), HogQLFilters(), self.team)
self.assertEqual(self._print_ast(select), f"SELECT event FROM events LIMIT {MAX_SELECT_RETURNED_ROWS}")
diff --git a/posthog/hogql/test/test_placeholders.py b/posthog/hogql/test/test_placeholders.py
index 927e586ff0cf..0882d6d2c5fb 100644
--- a/posthog/hogql/test/test_placeholders.py
+++ b/posthog/hogql/test/test_placeholders.py
@@ -34,8 +34,11 @@ class TestParser(SimpleTestCase):
self.assertEqual(finder.placeholder_fields, [["foo"]])
self.assertEqual(len(finder.placeholder_expressions), 1)
- def test_find_placeholders_chain_filters(self):
- finder = find_placeholders(parse_select("select 1 from events where {filters}"))
+ @parameterized.expand(
+ [("filters",), ("filters.native(timestamp)",), ("filters.previous",), ("filters.previous.native(timestamp)",)]
+ )
+ def test_find_placeholders_chain_filters(self, placeholder: str) -> None:
+ finder = find_placeholders(parse_select("select 1 from events where {" + placeholder + "}"))
self.assertTrue(finder.has_filters)
self.assertTrue(finder.has_date_filters)
diff --git a/posthog/hogql_queries/test/test_hogql_dashboard_filters.py b/posthog/hogql_queries/test/test_hogql_dashboard_filters.py
index 5a01dc0d1cf7..37aaff1c2a6f 100644
--- a/posthog/hogql_queries/test/test_hogql_dashboard_filters.py
+++ b/posthog/hogql_queries/test/test_hogql_dashboard_filters.py
@@ -7,6 +7,7 @@ from parameterized import parameterized
from posthog.schema import (
BIVisualizationNode,
BreakdownFilter,
+ CompareFilter,
DashboardFilter,
DateRange,
EventPropertyFilter,
@@ -66,6 +67,33 @@ class TestHogQLDashboardFilters(BaseTest):
assert updated.source.variables["plan"].value == "enterprise"
assert updated.source.variables["plan"].code_name == "plan"
+ def test_bi_comparison_uses_dashboard_dates_for_both_periods(self) -> None:
+ runner = self._create_hogql_runner(
+ query="""
+ (SELECT toStartOfDay(timestamp) AS bi_row_timestamp, count() AS count,
+ 'Current period' AS bi_comparison
+ FROM events WHERE {filters}
+ GROUP BY toStartOfDay(timestamp), bi_comparison ORDER BY bi_row_timestamp DESC LIMIT 1000)
+ UNION ALL
+ (SELECT toStartOfDay({filters.compareDate(timestamp)}) AS bi_row_timestamp, count() AS count,
+ 'Previous period' AS bi_comparison
+ FROM events WHERE {filters.previous}
+ GROUP BY toStartOfDay({filters.compareDate(timestamp)}), bi_comparison ORDER BY bi_row_timestamp DESC LIMIT 1000)
+ """,
+ filters=HogQLFilters(dateRange=DateRange(date_from="-7d"), compareFilter=CompareFilter(compare=True)),
+ )
+ runner.apply_dashboard_filters(DashboardFilter(date_from="2026-02-01", date_to="2026-02-28"))
+ sql = prepare_and_print_ast(
+ runner.to_query(),
+ dialect="clickhouse",
+ context=HogQLContext(team_id=self.team.pk, enable_select_queries=True),
+ )[0]
+ assert "2026-02-01" in sql
+ assert "2026-01-04" in sql
+ assert "addDays" in sql
+ assert "UNION ALL" in sql
+ assert "{filters" not in sql
+
@parameterized.expand(
[
("native", "{filters}"),
diff --git a/posthog/schema.py b/posthog/schema.py
index e3124c825685..b33e8b7a90d8 100644
--- a/posthog/schema.py
+++ b/posthog/schema.py
@@ -11071,6 +11071,7 @@ class BIConfig(BaseModel):
)
chartType: ChartDisplayType
columns: list[BIField]
+ compareFilter: CompareFilter | None = None
dateField: BIField | None = Field(
default=None,
description="Column that receives the worksheet and dashboard date range.",
@@ -27958,6 +27959,10 @@ class HogQLFilters(BaseModel):
"Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown."
),
)
+ compareFilter: CompareFilter | None = Field(
+ default=None,
+ description=("Comparison range consumed by {filters.previous} and {filters.compareDate(expr)}."),
+ )
dateRange: DateRange | None = None
filterTestAccounts: bool | None = None
interval: IntervalType | None = Field(
diff --git a/products/business_intelligence/frontend/biComparison.ts b/products/business_intelligence/frontend/biComparison.ts
new file mode 100644
index 000000000000..b0ef8bca11da
--- /dev/null
+++ b/products/business_intelligence/frontend/biComparison.ts
@@ -0,0 +1,34 @@
+import { BIConfig, BIField } from '~/queries/schema/schema-business-intelligence'
+import { escapeHogQLString } from '~/queries/utils'
+import { ChartDisplayType } from '~/types'
+
+import { getBIDateField } from './biQueryFilters'
+
+export function getBIComparisonDisabledReason(config: BIConfig): string | undefined {
+ if (!getBIDateField(config) || !config.dateRange?.date_from || config.dateRange.date_from === 'all') {
+ return 'Select a date column and a bounded date range first'
+ }
+ if (config.rows.length + config.columns.length > 2) {
+ return 'Period comparisons support up to two dimensions'
+ }
+ if (
+ ![
+ ChartDisplayType.Auto,
+ ChartDisplayType.ActionsTable,
+ ChartDisplayType.ActionsBar,
+ ChartDisplayType.ActionsStackedBar,
+ ChartDisplayType.ActionsLineGraph,
+ ChartDisplayType.ActionsAreaGraph,
+ ].includes(config.chartType)
+ ) {
+ return 'Use a table, bar, line, or area chart for period comparisons'
+ }
+}
+
+export function getBIComparisonDateExpression(field: BIField): string {
+ const bucket =
+ field.dateBucket && ['month', 'quarter', 'year'].includes(field.dateBucket)
+ ? `, ${escapeHogQLString(field.dateBucket)}`
+ : ''
+ return `{filters.compareDate(${field.expression}${bucket})}`
+}
diff --git a/products/business_intelligence/frontend/biEditorLogic.ts b/products/business_intelligence/frontend/biEditorLogic.ts
index 7a3fd7bdd1b3..4d0382e0490a 100644
--- a/products/business_intelligence/frontend/biEditorLogic.ts
+++ b/products/business_intelligence/frontend/biEditorLogic.ts
@@ -15,7 +15,7 @@ import {
BIQueryLimit,
BISort,
} from '~/queries/schema/schema-business-intelligence'
-import { DatabaseSchemaTable, DateRange } from '~/queries/schema/schema-general'
+import { CompareFilter, DatabaseSchemaTable, DateRange } from '~/queries/schema/schema-general'
import { ChartDisplayType } from '~/types'
import { captureBIEditorModeSelected } from 'products/business_intelligence/frontend/biEditorAnalytics'
@@ -347,6 +347,7 @@ export interface biEditorLogicActions {
setChartType: (chartType: ChartDisplayType) => {
chartType: ChartDisplayType
}
+ setCompareFilter: (compareFilter: CompareFilter) => { compareFilter: CompareFilter }
setDataPaneSearch: (search: string) => {
search: string
}
@@ -529,6 +530,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
}),
setChartType: (chartType: ChartDisplayType) => ({ chartType }),
setDateRange: (dateRange: DateRange) => ({ dateRange }),
+ setCompareFilter: (compareFilter: CompareFilter) => ({ compareFilter }),
setDateField: (field: BIField | null) => ({ field }),
setDataSource: (source: BIDataSource) => ({ source }),
setValueAggregation: (index: number, aggregation: BIAggregation) => ({ index, aggregation }),
@@ -650,6 +652,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
normalizeBIConfig({ ...config, rows: config.columns, columns: config.rows }),
setChartType: (config, { chartType }) => normalizeBIConfig({ ...config, chartType }),
setDateRange: (config, { dateRange }) => ({ ...config, dateRange }),
+ setCompareFilter: (config, { compareFilter }) => ({ ...config, compareFilter }),
setDateField: (config, { field }) => ({ ...config, dateField: field }),
setDataSource: (config, { source }) => setDataSourceInConfig(config, source),
setValueAggregation: (config, { index, aggregation }) => ({
@@ -838,6 +841,7 @@ export const biEditorLogic = kea<biEditorLogicType>([
removeFieldFromShelf: () => actions.runAfterChange(),
setChartType: () => actions.runAfterChange(),
setDateRange: () => actions.runAfterChange(),
+ setCompareFilter: () => actions.runAfterChange(),
setDateField: () => actions.runAfterChange(),
setDataSource: () => actions.runAfterChange(),
setValueAggregation: () => actions.runAfterChange(),
diff --git a/products/business_intelligence/frontend/biEditorTypes.test.ts b/products/business_intelligence/frontend/biEditorTypes.test.ts
index 601b932df995..7b688db69d67 100644
--- a/products/business_intelligence/frontend/biEditorTypes.test.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.test.ts
@@ -63,6 +63,41 @@ const countryField: BIField = {
}
describe('BI editor query generation', () => {
+ it.each(['month', 'quarter', 'year'] as const)(
+ 'aligns %s comparison buckets with calendar arithmetic',
+ (dateBucket) => {
+ const result = buildBIQuery({
+ ...DEFAULT_BI_CONFIG,
+ source: eventField.source,
+ dateRange: { date_from: 'mStart' },
+ compareFilter: { compare: true },
+ rows: [{ ...timestampField, dateBucket }],
+ dateField: { ...timestampField, expression: 'created_at' },
+ })!
+ expect(result.query).toContain(`{filters.compareDate(timestamp, '${dateBucket}')}`)
+ expect(result.query).toContain('{filters.previous.native(created_at)}')
+ }
+ )
+ test.each([undefined, '-1y'])('builds and persists period comparisons (%s)', (compare_to) => {
+ const config: BIConfig = {
+ ...DEFAULT_BI_CONFIG,
+ source: eventField.source,
+ dateRange: { date_from: 'mStart' },
+ compareFilter: { compare: true, compare_to },
+ rows: [{ ...timestampField, dateBucket: 'day' }],
+ columns: [eventField],
+ values: [{ field: revenueField, aggregation: 'sum' }],
+ }
+ const result = buildBIQuery(config)!
+ expect(result.query).toContain('UNION ALL')
+ expect(result.query).toContain('toStartOfDay({filters.compareDate(timestamp)}) AS bi_row_timestamp')
+ expect(result.query).toContain('{filters.previous}')
+ expect(result.query).toContain('ORDER BY bi_row_timestamp DESC')
+ expect(result.node.chartSettings?.seriesBreakdownColumn).toBe('bi_comparison')
+ expect(parseBIEditorState(BIEditorView.BI, config)?.config.compareFilter).toEqual(config.compareFilter)
+ expect(buildBIQuery({ ...config, dateRange: { date_from: 'all' } })?.query).not.toContain('UNION ALL')
+ })
+
test.each(['-28d', 'mStart', '-1mStart', 'qStart', '-1qStart', 'yStart'])(
'keeps %s relative in query filters instead of hardcoding the date in SQL',
(date_from) => {
diff --git a/products/business_intelligence/frontend/biEditorTypes.ts b/products/business_intelligence/frontend/biEditorTypes.ts
index 5e722b346377..4acbc4eebe82 100644
--- a/products/business_intelligence/frontend/biEditorTypes.ts
+++ b/products/business_intelligence/frontend/biEditorTypes.ts
@@ -28,6 +28,7 @@ import {
} from '~/queries/utils'
import { ChartDisplayType } from '~/types'
+import { getBIComparisonDisabledReason, getBIComparisonDateExpression } from './biComparison'
import { getBIFiltersPlaceholder, getBIQueryFilters, normalizeBIDates } from './biQueryFilters'
export enum BIEditorView {
@@ -125,6 +126,9 @@ export const DEFAULT_BI_CONFIG: BIConfig = {
export function normalizeBIConfig(config: BIConfig): BIConfig {
let normalized = normalizeBIDates(config)
+ if (normalized.compareFilter?.compare && getBIComparisonDisabledReason(normalized)) {
+ normalized = { ...normalized, compareFilter: { compare: false } }
+ }
const sort = normalized.sort
if (sort && !getBISortOptions(normalized).some((option) => option.key === sort.key)) {
normalized = { ...normalized, sort: null }
@@ -427,6 +431,15 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
}
const candidate = decodedConfig as Partial<BIConfig>
+ if (
+ candidate.compareFilter !== undefined &&
+ (!candidate.compareFilter ||
+ typeof candidate.compareFilter !== 'object' ||
+ (candidate.compareFilter.compare !== undefined && typeof candidate.compareFilter.compare !== 'boolean') ||
+ (candidate.compareFilter.compare_to != null && typeof candidate.compareFilter.compare_to !== 'string'))
+ ) {
+ return null
+ }
if (
candidate.dateRange !== undefined &&
(!candidate.dateRange ||
@@ -536,6 +549,7 @@ export function parseBIEditorState(editorViewValue: unknown, configValue: unknow
const config: BIConfig = {
source,
+ ...(candidate.compareFilter !== undefined ? { compareFilter: candidate.compareFilter } : {}),
...(candidate.dateField !== undefined
? { dateField: candidate.dateField === null ? null : parseBIFieldValue(candidate.dateField) }
: {}),
@@ -825,7 +839,7 @@ function computeBIQueryParts(config: BIConfig): BIQueryParts {
...configuredValues.map(({ expression }) => expression),
...config.filters.map((filter) => filter.customExpression || fieldExpression(filter.field)),
]
- const usedAliases = new Set(['bi_rows', 'bi_columns'])
+ const usedAliases = new Set(['bi_rows', 'bi_columns', 'bi_comparison'])
for (const dimension of [...rowDimensions, ...columnDimensions]) {
const preferred = dimension.alias
let suffix = 2
@@ -994,6 +1008,7 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
const { rowDimensions, columnDimensions, configuredValues } = computeBIQueryParts(config)
const dimensions = [...rowDimensions, ...columnDimensions]
+ const comparing = !!config.compareFilter?.compare
const dimensionExpressions = dimensions.map(({ field }) => fieldExpression(field))
const isPivotTable = config.chartType === ChartDisplayType.TwoDimensionalHeatmap
const hasSeriesBreakdown =
@@ -1012,7 +1027,7 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
.filter((axis): axis is BIPivotAxis => axis !== null)
.map(({ alias, expression }) => `${expression} AS ${alias}`)
: dimensions.map(({ field, alias }) =>
- hasSeriesBreakdown ? `${fieldExpression(field)} AS ${alias}` : fieldExpression(field)
+ hasSeriesBreakdown || comparing ? `${fieldExpression(field)} AS ${alias}` : fieldExpression(field)
)
const valueExpressions =
configuredValues.length > 0
@@ -1049,12 +1064,12 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
queryParts.push(`LIMIT ${normalizeBIConfig(config).limit}`)
- const query = queryParts.join('\n')
+ let query = queryParts.join('\n')
const chartDimensions = [...columnDimensions, ...rowDimensions]
const xDimension = chartDimensions.find(({ field }) => isDateTimeBIField(field)) ?? chartDimensions[0]
const breakdownDimension = chartDimensions.find((dimension) => dimension !== xDimension)
- const seriesSettings =
+ let seriesSettings: ChartSettings | undefined =
hasSeriesBreakdown && xDimension && breakdownDimension
? {
xAxis: { column: xDimension.alias },
@@ -1068,6 +1083,53 @@ export function buildBIQuery(config: BIConfig): BIQueryBuildResult | null {
}
: undefined
+ if (comparing) {
+ const orderDimension = dimensions.find(({ field }) =>
+ ['ASC', 'DESC'].some((direction) => orderByExpression === `${fieldExpression(field)} ${direction}`)
+ )
+ const comparisonOrder = orderDimension
+ ? `${orderDimension.alias} ${orderByExpression?.endsWith(' ASC') ? 'ASC' : 'DESC'}`
+ : orderByExpression
+ const periodLabel = config.compareFilter?.compare_to ? 'Comparison period' : 'Previous period'
+ const periodExpression = (label: string): string =>
+ breakdownDimension
+ ? `concat(${escapeHogQLString(label + ' · ')}, toString(${fieldExpression(breakdownDimension.field)}))`
+ : escapeHogQLString(label)
+ const buildPeriod = (previous: boolean): string => {
+ const expressions = dimensions.map(({ field }) =>
+ fieldExpression(
+ previous && isDateTimeBIField(field)
+ ? { ...field, expression: getBIComparisonDateExpression(field) }
+ : field
+ )
+ )
+ const select = [
+ ...dimensions.map(({ alias }, index) => `${expressions[index]} AS ${alias}`),
+ ...valueExpressions,
+ `${periodExpression(previous ? periodLabel : 'Current period')} AS bi_comparison`,
+ ]
+ const placeholder = getBIFiltersPlaceholder(config)
+ return [
+ `SELECT\n ${select.join(',\n ')}`,
+ `FROM ${escapePropertyAsHogQLIdentifier(config.source!.table)}`,
+ `WHERE\n ${[previous ? placeholder.replace('{filters', '{filters.previous') : placeholder, ...filters.map((filter) => `(${filter})`)].join('\n AND ')}`,
+ ...(expressions.length ? [`GROUP BY ${[...expressions, 'bi_comparison'].join(', ')}`] : []),
+ ...(comparisonOrder ? [`ORDER BY ${comparisonOrder}`] : []),
+ `LIMIT ${config.limit}`,
+ ].join('\n')
+ }
+ query = `(${buildPeriod(false)})\nUNION ALL\n(${buildPeriod(true)})`
+ seriesSettings = {
+ xAxis: { column: xDimension?.alias ?? 'bi_comparison' },
+ xAxisLabel: xDimension ? getBIFieldPillLabel(xDimension.field) : 'Period',
+ yAxis: configuredValues.length
+ ? configuredValues.map(({ alias }) => ({ column: alias }))
+ : [{ column: 'count' }],
+ seriesBreakdownColumn: xDimension ? 'bi_comparison' : undefined,
+ showLegend: true,
+ }
+ }
+
const pivotTableSettings = isPivotTable
? {
heatmap: {
diff --git a/products/business_intelligence/frontend/biQueryFilters.ts b/products/business_intelligence/frontend/biQueryFilters.ts
index 515f286e80e5..6c7e4afeab06 100644
--- a/products/business_intelligence/frontend/biQueryFilters.ts
+++ b/products/business_intelligence/frontend/biQueryFilters.ts
@@ -76,7 +76,7 @@ export function getBIFiltersPlaceholder(config: BIConfig): string {
}
export function getBIQueryFilters(config: BIConfig, filters?: HogQLFilters): HogQLFilters {
- return { ...filters, dateRange: config.dateRange ?? { date_from: 'all' } }
+ return { ...filters, dateRange: config.dateRange ?? { date_from: 'all' }, compareFilter: config.compareFilter }
}
export function mergeBIQuerySource(current: HogQLQuery, generated: HogQLQuery): HogQLQuery {
diff --git a/products/business_intelligence/frontend/components/BIDateControls.tsx b/products/business_intelligence/frontend/components/BIDateControls.tsx
index c2a9812eb305..33a3f4c10197 100644
--- a/products/business_intelligence/frontend/components/BIDateControls.tsx
+++ b/products/business_intelligence/frontend/components/BIDateControls.tsx
@@ -3,8 +3,10 @@ import { useActions, useValues } from 'kea'
import { IconCalendar } from '@posthog/icons'
import { LemonSelect } from '@posthog/lemon-ui'
+import { CompareFilter } from 'lib/components/CompareFilter/CompareFilter'
import { DateFilter } from 'lib/components/DateFilter/DateFilter'
+import { getBIComparisonDisabledReason } from '../biComparison'
import { biEditorLogic } from '../biEditorLogic'
import { BI_DATE_OPTIONS } from '../biEditorOptions'
import { isDateTimeBIField } from '../biEditorTypes'
@@ -12,7 +14,7 @@ import { getBIDateField } from '../biQueryFilters'
export function BIDateControls(): JSX.Element {
const { config, dataPaneFields } = useValues(biEditorLogic)
- const { setDateField, setDateRange } = useActions(biEditorLogic)
+ const { setDateField, setDateRange, setCompareFilter } = useActions(biEditorLogic)
const dateField = getBIDateField(config)
const dateFields = dataPaneFields.dimensions.filter(isDateTimeBIField)
if (dateField && !dateFields.some((field) => field.expression === dateField.expression)) {
@@ -57,6 +59,11 @@ export function BIDateControls(): JSX.Element {
</>
)}
/>
+ <CompareFilter
+ compareFilter={config.compareFilter}
+ updateCompareFilter={setCompareFilter}
+ disableReason={getBIComparisonDisabledReason(config)}
+ />
</div>
)
}
diff --git a/products/dashboards/frontend/generated/api.schemas.ts b/products/dashboards/frontend/generated/api.schemas.ts
index 9ddb9c251cc0..e1a9b62520e3 100644
--- a/products/dashboards/frontend/generated/api.schemas.ts
+++ b/products/dashboards/frontend/generated/api.schemas.ts
@@ -6775,6 +6775,8 @@ export interface PathsV2ActorsQueryApi {
export interface HogQLFiltersApi {
/** Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown. */
breakdownFilter?: BreakdownFilterApi | null
+ /** Comparison range consumed by {filters.previous} and {filters.compareDate(expr)}. */
+ compareFilter?: CompareFilterApi | null
dateRange?: DateRangeApi | null
filterTestAccounts?: boolean | null
/** Time granularity consumed by the {filters.interval} placeholder. Set from the dashboard-level interval. */
@@ -9338,6 +9340,7 @@ export interface BIValueApi {
export interface BIConfigApi {
chartType: ChartDisplayTypeApi
columns: BIFieldApi[]
+ compareFilter?: CompareFilterApi | null
/** Column that receives the worksheet and dashboard date range. */
dateField?: BIFieldApi | null
dateRange?: DateRangeApi | null
diff --git a/products/product_analytics/backend/models/test/test_insight_model.py b/products/product_analytics/backend/models/test/test_insight_model.py
index f50d4b1e405e..086a3757ea9c 100644
--- a/products/product_analytics/backend/models/test/test_insight_model.py
+++ b/products/product_analytics/backend/models/test/test_insight_model.py
@@ -173,6 +173,7 @@ class TestInsightModel(BaseTest):
"properties": None,
"interval": None,
"breakdownFilter": None,
+ "compareFilter": None,
},
),
(
@@ -191,6 +192,7 @@ class TestInsightModel(BaseTest):
"properties": None,
"interval": None,
"breakdownFilter": None,
+ "compareFilter": None,
},
),
(
@@ -209,6 +211,7 @@ class TestInsightModel(BaseTest):
"properties": None,
"interval": None,
"breakdownFilter": None,
+ "compareFilter": None,
},
),
(
@@ -235,6 +238,7 @@ class TestInsightModel(BaseTest):
"properties": [browser_equals_chrome],
"interval": None,
"breakdownFilter": None,
+ "compareFilter": None,
},
),
(
@@ -247,6 +251,7 @@ class TestInsightModel(BaseTest):
"properties": [browser_equals_firefox, browser_equals_chrome],
"interval": None,
"breakdownFilter": None,
+ "compareFilter": None,
},
),
]
diff --git a/products/product_analytics/frontend/generated/api.schemas.ts b/products/product_analytics/frontend/generated/api.schemas.ts
index c42176b47e5b..98693ff8f00e 100644
--- a/products/product_analytics/frontend/generated/api.schemas.ts
+++ b/products/product_analytics/frontend/generated/api.schemas.ts
@@ -5832,6 +5832,8 @@ export interface PathsV2ActorsQueryApi {
export interface HogQLFiltersApi {
/** Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown. */
breakdownFilter?: BreakdownFilterApi | null
+ /** Comparison range consumed by {filters.previous} and {filters.compareDate(expr)}. */
+ compareFilter?: CompareFilterApi | null
dateRange?: DateRangeApi | null
filterTestAccounts?: boolean | null
/** Time granularity consumed by the {filters.interval} placeholder. Set from the dashboard-level interval. */
@@ -8395,6 +8397,7 @@ export interface BIValueApi {
export interface BIConfigApi {
chartType: ChartDisplayTypeApi
columns: BIFieldApi[]
+ compareFilter?: CompareFilterApi | null
/** Column that receives the worksheet and dashboard date range. */
dateField?: BIFieldApi | null
dateRange?: DateRangeApi | null
diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.ts
index 818851286efa..7653c8ffa326 100644
--- a/services/mcp/src/api/generated.ts
+++ b/services/mcp/src/api/generated.ts
@@ -7166,6 +7166,8 @@ export namespace Schemas {
export interface HogQLFilters {
/** Breakdown consumed by the {filters.breakdown(...)} placeholder. Set from the dashboard-level breakdown. */
breakdownFilter?: BreakdownFilter | null;
+ /** Comparison range consumed by {filters.previous} and {filters.compareDate(expr)}. */
+ compareFilter?: CompareFilter | null;
dateRange?: DateRange | null;
filterTestAccounts?: boolean | null;
/** Time granularity consumed by the {filters.interval} placeholder. Set from the dashboard-level interval. */
@@ -10721,6 +10723,7 @@ export namespace Schemas {
export interface BIConfig {
chartType: ChartDisplayType;
columns: BIField[];
+ compareFilter?: CompareFilter | null;
/** Column that receives the worksheet and dashboard date range. */
dateField?: BIField | null;
dateRange?: DateRange | null;