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.

fix(revenue-analytics): unify person_id type across revenue sources (#88248)

Chris Shine2af8a07a9c8e
diff --git a/posthog/hogql/database/models.py b/posthog/hogql/database/models.py
index 73f54d5d65f3..81726d0ece3f 100644
--- a/posthog/hogql/database/models.py
+++ b/posthog/hogql/database/models.py
@@ -1,6 +1,7 @@
import datetime
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Literal, Optional, cast
+from uuid import UUID
from pydantic import (
BaseModel,
@@ -202,7 +203,9 @@ class UUIDDatabaseField(DatabaseField):
return UUIDType(nullable=self.is_nullable())
def default_value(self) -> Any:
- return "00000000-0000-0000-0000-000000000000"
+ # A `UUID` rather than its string form, so an empty `SelectQuery` prints a UUID-typed
+ # literal that still compares against a real UUID column.
+ return UUID("00000000-0000-0000-0000-000000000000")
class ExpressionField(DatabaseField):
diff --git a/posthog/hogql/database/schema/persons_revenue_analytics.py b/posthog/hogql/database/schema/persons_revenue_analytics.py
index fe1bee5f06cf..47e7e7963e2d 100644
--- a/posthog/hogql/database/schema/persons_revenue_analytics.py
+++ b/posthog/hogql/database/schema/persons_revenue_analytics.py
@@ -1,5 +1,7 @@
from collections import defaultdict
+import structlog
+
from posthog.hogql import ast
from posthog.hogql.context import HogQLContext
from posthog.hogql.database.models import (
@@ -9,7 +11,7 @@ from posthog.hogql.database.models import (
LazyJoinToAdd,
LazyTable,
LazyTableToAdd,
- StringDatabaseField,
+ UUIDDatabaseField,
)
from posthog.hogql.database.schema.util.revenue_analytics import get_table_kind, is_event_view
from posthog.hogql.errors import ResolutionError
@@ -17,14 +19,18 @@ from posthog.hogql.errors import ResolutionError
from posthog.exchange_rate_constants import EXCHANGE_RATE_DECIMAL_PRECISION
from posthog.schema_enums import DatabaseSchemaManagedViewTableKind
+logger = structlog.get_logger(__name__)
+
ZERO_DECIMAL = ast.Call(
name="toDecimal", args=[ast.Constant(value=0), ast.Constant(value=EXCHANGE_RATE_DECIMAL_PRECISION)]
)
FIELDS: dict[str, FieldOrTable] = {
"team_id": IntegerDatabaseField(name="team_id"),
- "person_id": StringDatabaseField(
- name="person_id", description="Person these revenue figures are aggregated for; join target for `persons.id`."
+ "person_id": UUIDDatabaseField(
+ name="person_id",
+ nullable=True,
+ description="Person these revenue figures are aggregated for; join target for `persons.id`.",
),
"revenue": DecimalDatabaseField(
name="revenue",
@@ -40,6 +46,8 @@ FIELDS: dict[str, FieldOrTable] = {
def _select_from_persons_revenue_analytics_table(context: HogQLContext) -> ast.SelectQuery | ast.SelectSetQuery:
+ from posthog.hogql.database.schema.persons import PersonsTable # noqa: PLC0415 — circular import
+
from products.revenue_analytics.backend.views import RevenueAnalyticsCustomerView, RevenueAnalyticsRevenueItemView
if not context.database:
@@ -72,9 +80,24 @@ def _select_from_persons_revenue_analytics_table(context: HogQLContext) -> ast.S
if is_event_view(customer_view.name):
person_id_chain = [RevenueAnalyticsCustomerView.get_generic_view_alias(), "id"]
else:
+ # The `persons` field comes from a user-defined warehouse join, so its name does not
+ # guarantee its target. Reading `id` off some other table casts to NULL below, which would
+ # hide that source's revenue in one unlabeled row, so require the real persons table.
persons_lazy_join = customer_view.fields.get("persons")
- if persons_lazy_join is not None and isinstance(persons_lazy_join, ast.LazyJoin):
+ persons_join_target = (
+ persons_lazy_join.resolve_table(context) if isinstance(persons_lazy_join, ast.LazyJoin) else None
+ )
+ if isinstance(persons_join_target, PersonsTable):
person_id_chain = [RevenueAnalyticsCustomerView.get_generic_view_alias(), "persons", "id"]
+ else:
+ # Skipping the source drops its revenue from this table with no other signal, so say
+ # so here. Otherwise a mistyped join name reads as "this source earned nothing".
+ logger.warning(
+ "persons_revenue_analytics_skipped_source",
+ team_id=context.team_id,
+ customer_view=customer_view.name,
+ persons_join_target=type(persons_join_target).__name__ if persons_join_target else None,
+ )
if person_id_chain is not None:
# Get the aggregated revenue by customer_id
@@ -112,7 +135,12 @@ def _select_from_persons_revenue_analytics_table(context: HogQLContext) -> ast.S
# and those views are, on their own, safe to query "without a `team_id` filter"
# since they're getting data from either the data warehouse (safe) or the events table (safe)
ast.Alias(alias="team_id", expr=ast.Constant(value=context.team_id)),
- ast.Alias(alias="person_id", expr=ast.Field(chain=person_id_chain)),
+ # Event views give a String id, warehouse views a UUID. A Variant cannot be a GROUP BY
+ # key, so both legs cast to the UUID that each of them ultimately holds.
+ ast.Alias(
+ alias="person_id",
+ expr=ast.Call(name="toUUID", args=[ast.Field(chain=person_id_chain)]),
+ ),
ast.Alias(
alias="revenue",
expr=ast.Call(
@@ -177,6 +205,15 @@ def _select_from_persons_revenue_analytics_table(context: HogQLContext) -> ast.S
ast.Alias(alias="mrr", expr=ast.Call(name="sum", args=[ast.Field(chain=["mrr"])])),
],
select_from=ast.JoinExpr(table=inner_query),
+ # A warehouse customer with no matching person gets the all-zeros UUID, because the LEFT JOIN
+ # fills the non-nullable `persons.id` with its type default rather than NULL. Dropping that
+ # key keeps unattributable revenue from reporting as one synthetic person that outranks every
+ # real one. A NULL from the cast compares to NULL here, so it is dropped too.
+ where=ast.CompareOperation(
+ op=ast.CompareOperationOp.NotEq,
+ left=ast.Field(chain=["person_id"]),
+ right=ast.Call(name="toUUID", args=[ast.Constant(value="00000000-0000-0000-0000-000000000000")]),
+ ),
group_by=[ast.Field(chain=["person_id"])],
)
@@ -218,11 +255,8 @@ def join_with_persons_revenue_analytics_table(
constraint=ast.JoinConstraint(
expr=ast.CompareOperation(
op=ast.CompareOperationOp.Eq,
- left=ast.Call(
- name="toString",
- args=[ast.Field(chain=[join_to_add.from_table, *join_to_add.lazy_join.from_field])],
- ),
- right=ast.Call(name="toString", args=[ast.Field(chain=[join_to_add.to_table, "person_id"])]),
+ left=ast.Field(chain=[join_to_add.from_table, *join_to_add.lazy_join.from_field]),
+ right=ast.Field(chain=[join_to_add.to_table, "person_id"]),
),
constraint_type="ON",
),
diff --git a/posthog/hogql/database/schema/test/__snapshots__/test_persons_revenue_analytics.ambr b/posthog/hogql/database/schema/test/__snapshots__/test_persons_revenue_analytics.ambr
index baa446dc399a..941237a006d5 100644
--- a/posthog/hogql/database/schema/test/__snapshots__/test_persons_revenue_analytics.ambr
+++ b/posthog/hogql/database/schema/test/__snapshots__/test_persons_revenue_analytics.ambr
@@ -10,7 +10,7 @@
WHERE and(equals(person.team_id, 99999), in(id,
(SELECT where_optimization.id AS id
FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), equals(where_optimization.id, '00000000-0000-0000-0000-000000000000')))))
+ WHERE and(equals(where_optimization.team_id, 99999), equals(where_optimization.id, '0193a0b1-2c3d-4e5f-8899-aabbccddeeff')))))
GROUP BY person.id
HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
LEFT JOIN
@@ -20,7 +20,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -188,8 +188,10 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))
- WHERE equals(persons.id, '00000000-0000-0000-0000-000000000000')
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons__revenue_analytics ON equals(persons.persons___id, persons__revenue_analytics.person_id)
+ WHERE equals(persons.id, '0193a0b1-2c3d-4e5f-8899-aabbccddeeff')
LIMIT 100 SETTINGS readonly=2,
max_execution_time=60,
allow_experimental_object_type=1,
@@ -222,7 +224,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -438,7 +440,9 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons__revenue_analytics ON equals(persons.persons___id, persons__revenue_analytics.person_id)
ORDER BY persons__revenue_analytics.revenue ASC
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
@@ -472,7 +476,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -688,7 +692,9 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons__revenue_analytics ON equals(persons.persons___id, persons__revenue_analytics.person_id)
ORDER BY persons__revenue_analytics.revenue ASC
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
@@ -724,7 +730,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -940,7 +946,9 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons__revenue_analytics ON equals(persons.persons___id, persons__revenue_analytics.person_id)
ORDER BY persons.id ASC
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
@@ -975,7 +983,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -1191,7 +1199,9 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons__revenue_analytics ON equals(persons.persons___id, persons__revenue_analytics.person_id)
ORDER BY persons.id ASC
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
@@ -1226,7 +1236,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -1442,7 +1452,9 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons__revenue_analytics ON equals(persons.persons___id, persons__revenue_analytics.person_id)
ORDER BY persons.id ASC
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
@@ -1478,7 +1490,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -1694,7 +1706,9 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons__revenue_analytics ON equals(persons.persons___id, persons__revenue_analytics.person_id)
ORDER BY persons.id ASC
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
@@ -1711,19 +1725,24 @@
use_hive_partitioning=0
'''
# ---
-# name: TestPersonsRevenueAnalytics.test_query_revenue_analytics_table_events
+# name: TestPersonsRevenueAnalytics.test_person_id_joins_directly_against_persons_id_0_events
'''
- SELECT persons_revenue_analytics.person_id AS person_id,
- persons_revenue_analytics.revenue AS revenue,
- persons_revenue_analytics.mrr AS mrr
+ SELECT persons.id AS id,
+ revenue.revenue AS revenue
FROM
+ (SELECT person.id AS id
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons
+ JOIN
(SELECT 99999 AS team_id,
person_id AS person_id,
sum(revenue) AS revenue,
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -1776,7 +1795,7 @@
'revenue_analytics.events.purchase' AS source_label,
toTimeZone(events.timestamp, 'UTC') AS timestamp,
timestamp AS created_at,
- isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription_id'), ''), 'null'), '^"|"$', '')) AS is_recurring,
+ 0 AS is_recurring,
NULL AS product_id,
toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS customer_id,
events.`$group_0` AS group_0_key,
@@ -1785,7 +1804,7 @@
events.`$group_3` AS group_3_key,
events.`$group_4` AS group_4_key,
NULL AS invoice_id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription_id'), ''), 'null'), '^"|"$', '') AS subscription_id,
+ NULL AS subscription_id,
toString(events.`$session_id`) AS session_id,
events.event AS event_name,
NULL AS coupon,
@@ -1829,7 +1848,7 @@
'revenue_analytics.events.purchase' AS source_label,
toTimeZone(events.timestamp, 'UTC') AS timestamp,
timestamp AS created_at,
- isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription_id'), ''), 'null'), '^"|"$', '')) AS is_recurring,
+ 0 AS is_recurring,
NULL AS product_id,
toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS customer_id,
events.`$group_0` AS group_0_key,
@@ -1838,7 +1857,7 @@
events.`$group_3` AS group_3_key,
events.`$group_4` AS group_4_key,
NULL AS invoice_id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription_id'), ''), 'null'), '^"|"$', '') AS subscription_id,
+ NULL AS subscription_id,
toString(events.`$session_id`) AS session_id,
events.event AS event_name,
NULL AS coupon,
@@ -1872,34 +1891,16 @@
toTimeZone(`revenue_analytics.events.purchase.subscription_events_revenue_view`.ended_at, 'UTC') AS timestamp,
accurateCastOrNull(0, 'Decimal64(10)') AS amount
FROM
- (SELECT subscription_id AS id,
- 'revenue_analytics.events.purchase' AS source_label,
- NULL AS plan_id,
- product_id AS product_id,
- toString(person_id) AS customer_id,
- NULL AS status,
- min_timestamp AS started_at,
- if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp_plus_dropoff_days) AS ended_at,
- NULL AS metadata
- FROM
- (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription_id'), ''), 'null'), '^"|"$', '') AS subscription_id,
- NULL AS product_id,
- min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp,
- max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp,
- addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_days
- FROM events
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
- WHERE and(equals(events.team_id, 99999), and(1, isNotNull(subscription_id)))
- GROUP BY subscription_id,
- person_id)
- ORDER BY started_at DESC) AS `revenue_analytics.events.purchase.subscription_events_revenue_view`
+ (SELECT '' AS id,
+ '' AS source_label,
+ '' AS plan_id,
+ '' AS product_id,
+ '' AS customer_id,
+ '' AS status,
+ toDateTime64('1970-01-01 00:00:00.000000', 6, 'UTC') AS started_at,
+ toDateTime64('1970-01-01 00:00:00.000000', 6, 'UTC') AS ended_at,
+ '' AS metadata
+ WHERE 0) AS `revenue_analytics.events.purchase.subscription_events_revenue_view`
WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfMonth(addDays(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), -60))), 0), ifNull(lessOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), 0))
ORDER BY timestamp DESC) AS
union
@@ -1909,8 +1910,9 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons_revenue_analytics
- ORDER BY persons_revenue_analytics.person_id ASC
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS revenue ON equals(persons.id, revenue.person_id)
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
max_execution_time=60,
@@ -1926,19 +1928,24 @@
use_hive_partitioning=0
'''
# ---
-# name: TestPersonsRevenueAnalytics.test_query_revenue_analytics_table_sources
+# name: TestPersonsRevenueAnalytics.test_person_id_joins_directly_against_persons_id_1_warehouse
'''
- SELECT persons_revenue_analytics.person_id AS person_id,
- persons_revenue_analytics.revenue AS revenue,
- persons_revenue_analytics.mrr AS mrr
+ SELECT persons.id AS id,
+ revenue.revenue AS revenue
FROM
+ (SELECT person.id AS id
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons
+ JOIN
(SELECT 99999 AS team_id,
person_id AS person_id,
sum(revenue) AS revenue,
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -2154,9 +2161,257 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS revenue ON equals(persons.id, revenue.person_id)
+ LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestPersonsRevenueAnalytics.test_person_id_joins_directly_against_persons_id_2_none
+ '''
+ SELECT persons.id AS id,
+ revenue.revenue AS revenue
+ FROM
+ (SELECT person.id AS id
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons
+ JOIN
+ (SELECT 99999 AS team_id,
+ toUUIDOrNull('00000000-0000-0000-0000-000000000000') AS person_id,
+ 0 AS revenue,
+ 0 AS mrr
+ WHERE 0) AS revenue ON equals(persons.id, revenue.person_id)
+ LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestPersonsRevenueAnalytics.test_query_revenue_analytics_table_events
+ '''
+ SELECT persons_revenue_analytics.person_id AS person_id,
+ persons_revenue_analytics.revenue AS revenue,
+ persons_revenue_analytics.mrr AS mrr
+ FROM
+ (SELECT 99999 AS team_id,
+ person_id AS person_id,
+ sum(revenue) AS revenue,
+ sum(mrr) AS mrr
+ FROM
+ (SELECT 99999 AS team_id,
+ accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id,
+ coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
+ coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
+ FROM
+ (SELECT toString(persons.id) AS id,
+ 'revenue_analytics.events.purchase' AS source_label,
+ persons.created_at AS timestamp,
+ persons.properties___name AS name,
+ persons.properties___email AS email,
+ persons.properties___phone AS phone,
+ persons.properties___address AS address,
+ persons.properties___metadata AS metadata,
+ persons.`properties___$geoip_country_name` AS country,
+ formatDateTime(toStartOfMonth(persons.created_at), '%Y-%m') AS cohort,
+ NULL AS initial_coupon,
+ NULL AS initial_coupon_id
+ FROM
+ (SELECT person.id AS id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '') AS properties___name,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'phone'), ''), 'null'), '^"|"$', '') AS properties___phone,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'address'), ''), 'null'), '^"|"$', '') AS properties___address,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'metadata'), ''), 'null'), '^"|"$', '') AS properties___metadata,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, '$geoip_country_name'), ''), 'null'), '^"|"$', '') AS `properties___$geoip_country_name`,
+ toTimeZone(person.created_at, 'UTC') AS created_at
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
+ (SELECT person.id AS id, max(person.version) AS version
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons
+ INNER JOIN
+ (SELECT DISTINCT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE equals(events.team_id, 99999)) AS events ON equals(persons.id, events.person_id)
+ ORDER BY persons.created_at DESC) AS revenue_analytics_customer
+ LEFT JOIN
+ (SELECT revenue_analytics_revenue_item.customer_id AS customer_id,
+ sum(revenue_analytics_revenue_item.amount) AS revenue
+ FROM
+ (SELECT toString(events.uuid) AS id,
+ toString(events.uuid) AS invoice_item_id,
+ 'revenue_analytics.events.purchase' AS source_label,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ timestamp AS created_at,
+ isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription_id'), ''), 'null'), '^"|"$', '')) AS is_recurring,
+ NULL AS product_id,
+ toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS customer_id,
+ events.`$group_0` AS group_0_key,
+ events.`$group_1` AS group_1_key,
+ events.`$group_2` AS group_2_key,
+ events.`$group_3` AS group_3_key,
+ events.`$group_4` AS group_4_key,
+ NULL AS invoice_id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription_id'), ''), 'null'), '^"|"$', '') AS subscription_id,
+ toString(events.`$session_id`) AS session_id,
+ events.event AS event_name,
+ NULL AS coupon,
+ coupon AS coupon_id,
+ 'USD' AS original_currency,
+ accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'revenue'), ''), 'null'), '^"|"$', ''), 'Decimal64(10)') AS original_amount,
+ in(original_currency,
+ ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider,
+ if(enable_currency_aware_divider, accurateCastOrNull(1, 'Decimal64(10)'), accurateCastOrNull(100, 'Decimal64(10)')) AS currency_aware_divider,
+ divideDecimal(original_amount, currency_aware_divider) AS currency_aware_amount,
+ 'USD' AS currency,
+ if(isNull('USD'), accurateCastOrNull(currency_aware_amount, 'Decimal64(10)'), if(equals('USD', 'USD'), toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)) = 0, toDecimal128(0, 10), multiplyDecimal(divideDecimal(toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)) = 0, toDecimal128(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)))))) AS amount
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), and(equals(events.event, 'purchase'), 1, isNotNull(amount)))
+ ORDER BY timestamp DESC) AS revenue_analytics_revenue_item
+ GROUP BY customer_id) AS revenue_agg ON equals(revenue_analytics_customer.id, revenue_agg.customer_id)
+ LEFT JOIN
+ (SELECT `revenue_analytics.events.purchase.mrr_events_revenue_view`.customer_id AS customer_id,
+ sum(`revenue_analytics.events.purchase.mrr_events_revenue_view`.mrr) AS mrr
+ FROM
+ (SELECT union.source_label AS source_label,
+ union.customer_id AS customer_id,
+ union.subscription_id AS subscription_id,
+ argMax(union.amount, union.timestamp) AS mrr
+ FROM
+ (SELECT revenue_item.source_label AS source_label,
+ revenue_item.customer_id AS customer_id,
+ revenue_item.subscription_id AS subscription_id,
+ toStartOfMonth(toTimeZone(revenue_item.timestamp, 'UTC')) AS timestamp,
+ sum(revenue_item.amount) AS amount
+ FROM
+ (SELECT toString(events.uuid) AS id,
+ toString(events.uuid) AS invoice_item_id,
+ 'revenue_analytics.events.purchase' AS source_label,
+ toTimeZone(events.timestamp, 'UTC') AS timestamp,
+ timestamp AS created_at,
+ isNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription_id'), ''), 'null'), '^"|"$', '')) AS is_recurring,
+ NULL AS product_id,
+ toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS customer_id,
+ events.`$group_0` AS group_0_key,
+ events.`$group_1` AS group_1_key,
+ events.`$group_2` AS group_2_key,
+ events.`$group_3` AS group_3_key,
+ events.`$group_4` AS group_4_key,
+ NULL AS invoice_id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription_id'), ''), 'null'), '^"|"$', '') AS subscription_id,
+ toString(events.`$session_id`) AS session_id,
+ events.event AS event_name,
+ NULL AS coupon,
+ coupon AS coupon_id,
+ 'USD' AS original_currency,
+ accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'revenue'), ''), 'null'), '^"|"$', ''), 'Decimal64(10)') AS original_amount,
+ in(original_currency,
+ ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider,
+ if(enable_currency_aware_divider, accurateCastOrNull(1, 'Decimal64(10)'), accurateCastOrNull(100, 'Decimal64(10)')) AS currency_aware_divider,
+ divideDecimal(original_amount, currency_aware_divider) AS currency_aware_amount,
+ 'USD' AS currency,
+ if(isNull('USD'), accurateCastOrNull(currency_aware_amount, 'Decimal64(10)'), if(equals('USD', 'USD'), toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)) = 0, toDecimal128(0, 10), multiplyDecimal(divideDecimal(toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)) = 0, toDecimal128(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)))))) AS amount
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), and(equals(events.event, 'purchase'), 1, isNotNull(amount)))
+ ORDER BY timestamp DESC) AS revenue_item
+ WHERE and(revenue_item.is_recurring, isNotNull(revenue_item.subscription_id), ifNull(greaterOrEquals(timestamp, toStartOfMonth(addDays(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), -60))), 0), ifNull(lessOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), 0))
+ GROUP BY revenue_item.source_label,
+ revenue_item.customer_id,
+ revenue_item.subscription_id, timestamp
+ ORDER BY timestamp DESC
+ UNION ALL SELECT `revenue_analytics.events.purchase.subscription_events_revenue_view`.source_label AS source_label,
+ `revenue_analytics.events.purchase.subscription_events_revenue_view`.customer_id AS customer_id,
+ `revenue_analytics.events.purchase.subscription_events_revenue_view`.id AS subscription_id,
+ toTimeZone(`revenue_analytics.events.purchase.subscription_events_revenue_view`.ended_at, 'UTC') AS timestamp,
+ accurateCastOrNull(0, 'Decimal64(10)') AS amount
+ FROM
+ (SELECT subscription_id AS id,
+ 'revenue_analytics.events.purchase' AS source_label,
+ NULL AS plan_id,
+ product_id AS product_id,
+ toString(person_id) AS customer_id,
+ NULL AS status,
+ min_timestamp AS started_at,
+ if(greater(max_timestamp_plus_dropoff_days, today()), NULL, max_timestamp_plus_dropoff_days) AS ended_at,
+ NULL AS metadata
+ FROM
+ (SELECT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id,
+ replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'subscription_id'), ''), 'null'), '^"|"$', '') AS subscription_id,
+ NULL AS product_id,
+ min(toTimeZone(events.timestamp, 'UTC')) AS min_timestamp,
+ max(toTimeZone(events.timestamp, 'UTC')) AS max_timestamp,
+ addDays(max_timestamp, 45.0) AS max_timestamp_plus_dropoff_days
+ FROM events
+ LEFT OUTER JOIN
+ (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
+ person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), and(1, isNotNull(subscription_id)))
+ GROUP BY subscription_id,
+ person_id)
+ ORDER BY started_at DESC) AS `revenue_analytics.events.purchase.subscription_events_revenue_view`
+ WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfMonth(addDays(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), -60))), 0), ifNull(lessOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), 0))
+ ORDER BY timestamp DESC) AS
+ union
+ GROUP BY source_label,
+ customer_id,
+ subscription_id
+ ORDER BY customer_id ASC,
+ subscription_id ASC) AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
+ GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
GROUP BY person_id) AS persons_revenue_analytics
- ORDER BY persons_revenue_analytics.mrr DESC,
- persons_revenue_analytics.revenue DESC
+ ORDER BY persons_revenue_analytics.person_id ASC
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
max_execution_time=60,
@@ -2172,7 +2427,7 @@
use_hive_partitioning=0
'''
# ---
-# name: TestPersonsRevenueAnalytics.test_revenue_aggregated_per_person_across_multiple_customers
+# name: TestPersonsRevenueAnalytics.test_query_revenue_analytics_table_sources
'''
SELECT persons_revenue_analytics.person_id AS person_id,
persons_revenue_analytics.revenue AS revenue,
@@ -2184,7 +2439,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -2400,8 +2655,11 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
GROUP BY person_id) AS persons_revenue_analytics
- WHERE equals(persons_revenue_analytics.person_id, toUUIDOrNull('00000000-0000-4000-8000-000000000000'))
+ ORDER BY persons_revenue_analytics.mrr DESC,
+ persons_revenue_analytics.revenue DESC
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
max_execution_time=60,
@@ -2417,29 +2675,166 @@
use_hive_partitioning=0
'''
# ---
-# name: TestPersonsRevenueAnalytics.test_revenue_aggregated_per_person_across_multiple_customers.1
+# name: TestPersonsRevenueAnalytics.test_revenue_aggregated_per_person_across_event_and_warehouse_sources
'''
- SELECT persons.id AS id,
- persons__revenue_analytics.revenue AS `$virt_revenue`,
- persons__revenue_analytics.mrr AS `$virt_mrr`
+ SELECT persons_revenue_analytics.person_id AS person_id, persons_revenue_analytics.revenue AS revenue, persons_revenue_analytics.mrr AS mrr
+ FROM (
+ SELECT 99999 AS team_id, person_id AS person_id, sum(revenue) AS revenue, sum(mrr) AS mrr
+ FROM (
+ SELECT 99999 AS team_id, accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id, coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue, coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
+ FROM (
+ SELECT toString(persons.id) AS id, 'revenue_analytics.events.purchase' AS source_label, persons.created_at AS timestamp, persons.properties___name AS name, persons.properties___email AS email, persons.properties___phone AS phone, persons.properties___address AS address, persons.properties___metadata AS metadata, persons.`properties___$geoip_country_name` AS country, formatDateTime(toStartOfMonth(persons.created_at), '%Y-%m') AS cohort, NULL AS initial_coupon, NULL AS initial_coupon_id
+ FROM (
+ SELECT person.id AS id, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'name'), ''), 'null'), '^"|"$', '') AS properties___name, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'email'), ''), 'null'), '^"|"$', '') AS properties___email, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'phone'), ''), 'null'), '^"|"$', '') AS properties___phone, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'address'), ''), 'null'), '^"|"$', '') AS properties___address, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'metadata'), ''), 'null'), '^"|"$', '') AS properties___metadata, replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, '$geoip_country_name'), ''), 'null'), '^"|"$', '') AS `properties___$geoip_country_name`, toTimeZone(person.created_at, 'UTC') AS created_at
+ FROM person
+ WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version), (
+ SELECT person.id AS id, max(person.version) AS version
+ FROM person WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS persons
+ INNER JOIN (
+ SELECT DISTINCT if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id) AS person_id
+ FROM events
+ LEFT OUTER JOIN (
+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE equals(events.team_id, 99999)) AS events ON equals(persons.id, events.person_id)
+ ORDER BY persons.created_at DESC) AS revenue_analytics_customer
+ LEFT JOIN (
+ SELECT revenue_analytics_revenue_item.customer_id AS customer_id, sum(revenue_analytics_revenue_item.amount) AS revenue
+ FROM (
+ SELECT toString(events.uuid) AS id, toString(events.uuid) AS invoice_item_id, 'revenue_analytics.events.purchase' AS source_label, toTimeZone(events.timestamp, 'UTC') AS timestamp, timestamp AS created_at, 0 AS is_recurring, NULL AS product_id, toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS customer_id, events.`$group_0` AS group_0_key, events.`$group_1` AS group_1_key, events.`$group_2` AS group_2_key, events.`$group_3` AS group_3_key, events.`$group_4` AS group_4_key, NULL AS invoice_id, NULL AS subscription_id, toString(events.`$session_id`) AS session_id, events.event AS event_name, NULL AS coupon, coupon AS coupon_id, 'USD' AS original_currency, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'revenue'), ''), 'null'), '^"|"$', ''), 'Decimal64(10)') AS original_amount, in(original_currency, ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider, if(enable_currency_aware_divider, accurateCastOrNull(1, 'Decimal64(10)'), accurateCastOrNull(100, 'Decimal64(10)')) AS currency_aware_divider, divideDecimal(original_amount, currency_aware_divider) AS currency_aware_amount, 'GBP' AS currency, if(isNull('USD'), accurateCastOrNull(currency_aware_amount, 'Decimal64(10)'), if(equals('USD', 'GBP'), toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)) = 0, toDecimal128(0, 10), multiplyDecimal(divideDecimal(toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)) = 0, toDecimal128(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'GBP', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)))))) AS amount
+ FROM events
+ LEFT OUTER JOIN (
+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), and(equals(events.event, 'purchase'), 1, isNotNull(amount)))
+ ORDER BY timestamp DESC) AS revenue_analytics_revenue_item
+ GROUP BY customer_id) AS revenue_agg ON equals(revenue_analytics_customer.id, revenue_agg.customer_id)
+ LEFT JOIN (
+ SELECT `revenue_analytics.events.purchase.mrr_events_revenue_view`.customer_id AS customer_id, sum(`revenue_analytics.events.purchase.mrr_events_revenue_view`.mrr) AS mrr
+ FROM (
+ SELECT union.source_label AS source_label, union.customer_id AS customer_id, union.subscription_id AS subscription_id, argMax(union.amount, union.timestamp) AS mrr
+ FROM (
+ SELECT revenue_item.source_label AS source_label, revenue_item.customer_id AS customer_id, revenue_item.subscription_id AS subscription_id, toStartOfMonth(toTimeZone(revenue_item.timestamp, 'UTC')) AS timestamp, sum(revenue_item.amount) AS amount
+ FROM (
+ SELECT toString(events.uuid) AS id, toString(events.uuid) AS invoice_item_id, 'revenue_analytics.events.purchase' AS source_label, toTimeZone(events.timestamp, 'UTC') AS timestamp, timestamp AS created_at, 0 AS is_recurring, NULL AS product_id, toString(if(not(empty(events__override.distinct_id)), events__override.person_id, events.person_id)) AS customer_id, events.`$group_0` AS group_0_key, events.`$group_1` AS group_1_key, events.`$group_2` AS group_2_key, events.`$group_3` AS group_3_key, events.`$group_4` AS group_4_key, NULL AS invoice_id, NULL AS subscription_id, toString(events.`$session_id`) AS session_id, events.event AS event_name, NULL AS coupon, coupon AS coupon_id, 'USD' AS original_currency, accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.properties, 'revenue'), ''), 'null'), '^"|"$', ''), 'Decimal64(10)') AS original_amount, in(original_currency, ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider, if(enable_currency_aware_divider, accurateCastOrNull(1, 'Decimal64(10)'), accurateCastOrNull(100, 'Decimal64(10)')) AS currency_aware_divider, divideDecimal(original_amount, currency_aware_divider) AS currency_aware_amount, 'GBP' AS currency, if(isNull('USD'), accurateCastOrNull(currency_aware_amount, 'Decimal64(10)'), if(equals('USD', 'GBP'), toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)) = 0, toDecimal128(0, 10), multiplyDecimal(divideDecimal(toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)) = 0, toDecimal128(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'USD', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', 'GBP', toDate(toTimeZone(events.timestamp, 'UTC')), toDecimal64(0, 10)))))) AS amount
+ FROM events
+ LEFT OUTER JOIN (
+ SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id, person_distinct_id_overrides.distinct_id AS distinct_id
+ FROM person_distinct_id_overrides
+ WHERE equals(person_distinct_id_overrides.team_id, 99999)
+ GROUP BY person_distinct_id_overrides.distinct_id
+ HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS events__override ON equals(events.distinct_id, events__override.distinct_id)
+ WHERE and(equals(events.team_id, 99999), and(equals(events.event, 'purchase'), 1, isNotNull(amount)))
+ ORDER BY timestamp DESC) AS revenue_item
+ WHERE and(revenue_item.is_recurring, isNotNull(revenue_item.subscription_id), ifNull(greaterOrEquals(timestamp, toStartOfMonth(addDays(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), -60))), 0), ifNull(lessOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), 0))
+ GROUP BY revenue_item.source_label, revenue_item.customer_id, revenue_item.subscription_id, timestamp
+ ORDER BY timestamp DESC
+ UNION ALL
+ SELECT `revenue_analytics.events.purchase.subscription_events_revenue_view`.source_label AS source_label, `revenue_analytics.events.purchase.subscription_events_revenue_view`.customer_id AS customer_id, `revenue_analytics.events.purchase.subscription_events_revenue_view`.id AS subscription_id, toTimeZone(`revenue_analytics.events.purchase.subscription_events_revenue_view`.ended_at, 'UTC') AS timestamp, accurateCastOrNull(0, 'Decimal64(10)') AS amount
+ FROM (
+ SELECT '' AS id, '' AS source_label, '' AS plan_id, '' AS product_id, '' AS customer_id, '' AS status, toDateTime64('1970-01-01 00:00:00.000000', 6, 'UTC') AS started_at, toDateTime64('1970-01-01 00:00:00.000000', 6, 'UTC') AS ended_at, '' AS metadata
+ WHERE 0) AS `revenue_analytics.events.purchase.subscription_events_revenue_view` WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfMonth(addDays(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), -60))), 0), ifNull(lessOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), 0))
+ ORDER BY timestamp DESC) AS
+ union
+ GROUP BY source_label, customer_id, subscription_id
+ ORDER BY customer_id ASC, subscription_id ASC) AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
+ GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id)
+ UNION ALL
+ SELECT 99999 AS team_id, accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id, coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue, coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
+ FROM (
+ SELECT inner.id AS id, inner.source_label AS source_label, inner.timestamp AS timestamp, inner.name AS name, inner.email AS email, inner.phone AS phone, inner.address AS address, if(notEquals(JSONExtractString(inner.metadata, 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id_source', 'customer'))), if(notEquals(inner.resolved_distinct_id, ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata, '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata, '{}'), k), JSONExtractKeys(ifNull(inner.metadata, '{}')))), map('posthog_person_distinct_id', inner.resolved_distinct_id, 'posthog_person_distinct_id_source', inner.resolved_source))), inner.metadata)) AS metadata, inner.country AS country, inner.cohort AS cohort, inner.initial_coupon AS initial_coupon, inner.initial_coupon_id AS initial_coupon_id
+ FROM (
+ SELECT outer.id AS id, 'stripe.posthog_test' AS source_label, parseDateTime64BestEffortOrNull(toString(outer.created), 6, 'UTC') AS timestamp, outer.name AS name, outer.email AS email, outer.phone AS phone, outer.address AS address, outer.metadata AS metadata, JSONExtractString(address, 'country') AS country, cohort_inner.cohort AS cohort, cohort_inner.initial_coupon AS initial_coupon, cohort_inner.initial_coupon_id AS initial_coupon_id, ifNull(resolved.resolved_distinct_id, '') AS resolved_distinct_id, ifNull(resolved.resolved_source, '') AS resolved_source
+ FROM (
+ SELECT *
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_customers/posthog_test_stripe_customer/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `name` String, `email` String, `phone` String, `address` String, `created` DateTime, `metadata` String')) AS outer
+ LEFT JOIN (
+ SELECT invoice.customer AS customer_id, formatDateTime(toStartOfMonth(min(parseDateTime64BestEffortOrNull(toString(invoice.created), 6, 'UTC'))), '%Y-%m') AS cohort, argMin(JSONExtractString(invoice.discount, 'coupon', 'name'), parseDateTime64BestEffortOrNull(toString(invoice.created), 6, 'UTC')) AS initial_coupon, argMin(JSONExtractString(invoice.discount, 'coupon', 'id'), parseDateTime64BestEffortOrNull(toString(invoice.created), 6, 'UTC')) AS initial_coupon_id
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_invoices/posthog_test_stripe_invoice/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `tax` Int64, `paid` UInt8, `lines` String, `total` Int64, `charge` String, `issuer` String, `number` String, `object` String, `status` String, `created` DateTime, `currency` String, `customer` String, `discount` String, `due_date` DateTime, `livemode` UInt8, `metadata` String, `subtotal` Int64, `attempted` UInt8, `discounts` String, `rendering` String, `amount_due` Int64, `amount_paid` Int64, `description` String, `invoice_pdf` String, `account_name` String, `auto_advance` UInt8, `effective_at` DateTime, `subscription` String, `attempt_count` UInt8, `automatic_tax` String, `customer_name` String, `period_end_at` DateTime, `billing_reason` String, `customer_email` String, `ending_balance` Int64, `payment_intent` String, `account_country` String, `amount_shipping` Int64, `period_start_at` DateTime, `amount_remaining` Int64, `customer_address` String, `customer_tax_ids` String, `paid_out_of_band` UInt8, `payment_settings` String, `starting_balance` Int64, `collection_method` String, `default_tax_rates` String, `total_tax_amounts` String, `hosted_invoice_url` String, `status_transitions` String, `customer_tax_exempt` String, `total_excluding_tax` Int64, `subscription_details` String, `webhooks_delivered_at` DateTime, `subtotal_excluding_tax` Int64, `total_discount_amounts` String, `pre_payment_credit_notes_amount` Int64, `post_payment_credit_notes_amount` Int64') AS invoice
+ GROUP BY invoice.customer) AS cohort_inner ON equals(cohort_inner.customer_id, outer.id)
+ LEFT JOIN (
+ SELECT child_meta.customer_id AS customer_id, argMax(child_meta.distinct_id, child_meta.created_at) AS resolved_distinct_id, argMax(child_meta.source_ref, child_meta.created_at) AS resolved_source
+ FROM (
+ SELECT posthog_test_stripe_invoice.customer AS customer_id, JSONExtractString(posthog_test_stripe_invoice.metadata, 'posthog_person_distinct_id') AS distinct_id, concat('invoice', '::', ifNull(toString(posthog_test_stripe_invoice.id), '')) AS source_ref, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6, 'UTC') AS created_at
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_invoices/posthog_test_stripe_invoice/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `tax` Int64, `paid` UInt8, `lines` String, `total` Int64, `charge` String, `issuer` String, `number` String, `object` String, `status` String, `created` DateTime, `currency` String, `customer` String, `discount` String, `due_date` DateTime, `livemode` UInt8, `metadata` String, `subtotal` Int64, `attempted` UInt8, `discounts` String, `rendering` String, `amount_due` Int64, `amount_paid` Int64, `description` String, `invoice_pdf` String, `account_name` String, `auto_advance` UInt8, `effective_at` DateTime, `subscription` String, `attempt_count` UInt8, `automatic_tax` String, `customer_name` String, `period_end_at` DateTime, `billing_reason` String, `customer_email` String, `ending_balance` Int64, `payment_intent` String, `account_country` String, `amount_shipping` Int64, `period_start_at` DateTime, `amount_remaining` Int64, `customer_address` String, `customer_tax_ids` String, `paid_out_of_band` UInt8, `payment_settings` String, `starting_balance` Int64, `collection_method` String, `default_tax_rates` String, `total_tax_amounts` String, `hosted_invoice_url` String, `status_transitions` String, `customer_tax_exempt` String, `total_excluding_tax` Int64, `subscription_details` String, `webhooks_delivered_at` DateTime, `subtotal_excluding_tax` Int64, `total_discount_amounts` String, `pre_payment_credit_notes_amount` Int64, `post_payment_credit_notes_amount` Int64') AS posthog_test_stripe_invoice
+ WHERE notEquals(JSONExtractString(posthog_test_stripe_invoice.metadata, 'posthog_person_distinct_id'), '')) AS child_meta
+ GROUP BY child_meta.customer_id) AS resolved ON equals(resolved.customer_id, outer.id)) AS inner
+ ORDER BY timestamp DESC
+ LIMIT 1 BY id) AS revenue_analytics_customer
+ LEFT JOIN (
+ SELECT persons.id AS id, persons__pdi.distinct_id AS revenue_analytics_customer__persons___pdi___distinct_id
+ FROM (
+ SELECT argMax(person.id, person.version) AS persons___id, person.id AS id
+ FROM person
+ WHERE equals(person.team_id, 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons
+ LEFT JOIN (
+ SELECT argMax(person_distinct_id2.person_id, person_distinct_id2.version) AS person_id, person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id, 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted, person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS persons__pdi ON equals(persons.persons___id, persons__pdi.person_id)) AS revenue_analytics_customer__persons ON equals(revenue_analytics_customer.id, revenue_analytics_customer__persons.revenue_analytics_customer__persons___pdi___distinct_id)
+ LEFT JOIN (
+ SELECT revenue_analytics_revenue_item.customer_id AS customer_id, sum(revenue_analytics_revenue_item.amount) AS revenue
+ FROM (
+ SELECT if(ifNull(greater(invoice.period_months, 1), 0), concat(ifNull(toString(invoice.invoice_item_id), ''), '_', ifNull(toString(invoice.month_index), '')), invoice.invoice_item_id) AS id, invoice.invoice_item_id AS invoice_item_id, 'stripe.posthog_test' AS source_label, addMonths(invoice.timestamp, invoice.month_index) AS timestamp, invoice.created_at AS created_at, ifNull(notEmpty(invoice.subscription_id), 0) AS is_recurring, invoice.product_id AS product_id, invoice.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, invoice.id AS invoice_id, invoice.subscription_id AS subscription_id, NULL AS session_id, NULL AS event_name, JSONExtractString(invoice.discount, 'coupon', 'name') AS coupon, JSONExtractString(invoice.discount, 'coupon', 'id') AS coupon_id, upper(invoice.currency) AS original_currency, accurateCastOrNull(invoice.amount_captured, 'Decimal64(10)') AS original_amount, in(original_currency, ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider, if(enable_currency_aware_divider, accurateCastOrNull(1, 'Decimal64(10)'), accurateCastOrNull(100, 'Decimal64(10)')) AS currency_aware_divider, divideDecimal(original_amount, currency_aware_divider) AS currency_aware_amount, 'GBP' AS currency, divideDecimal(if(equals(original_currency, currency), toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal128(0, 10), multiplyDecimal(divideDecimal(toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal128(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))), accurateCastOrNull(invoice.period_months, 'Decimal64(10)')) AS amount
+ FROM (
+ SELECT posthog_test_stripe_invoice.id AS id, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6, 'UTC') AS created_at, posthog_test_stripe_invoice.customer AS customer_id, posthog_test_stripe_invoice.subscription AS subscription_id, posthog_test_stripe_invoice.discount AS discount, arrayJoin(JSONExtractArrayRaw(assumeNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(posthog_test_stripe_invoice.lines, 'data'), ''), 'null'), '^"|"$', '')))) AS data, JSONExtractString(data, 'id') AS invoice_item_id, JSONExtractUInt(data, 'amount') AS amount_before_discount, coalesce(arraySum(arrayMap(x -> JSONExtractInt(x, 'amount'), JSONExtractArrayRaw(data, 'discount_amounts'))), 0) AS discount_amount, greatest(minus(amount_before_discount, discount_amount), 0) AS amount_captured, JSONExtractString(data, 'currency') AS currency, JSONExtractString(data, 'price', 'product') AS product_id, fromUnixTimestamp(JSONExtractUInt(data, 'period', 'start')) AS period_start, fromUnixTimestamp(JSONExtractUInt(data, 'period', 'end')) AS period_end, greatest(toInt16(round(divide(dateDiff('day', ifNull(period_start, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6, 'UTC')), ifNull(period_end, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6, 'UTC'))), 30.44))), 1) AS period_months, arrayJoin(range(0, period_months)) AS month_index, ifNull(period_start, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6, 'UTC')) AS timestamp
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_invoices/posthog_test_stripe_invoice/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `tax` Int64, `paid` UInt8, `lines` String, `total` Int64, `charge` String, `issuer` String, `number` String, `object` String, `status` String, `created` DateTime, `currency` String, `customer` String, `discount` String, `due_date` DateTime, `livemode` UInt8, `metadata` String, `subtotal` Int64, `attempted` UInt8, `discounts` String, `rendering` String, `amount_due` Int64, `amount_paid` Int64, `description` String, `invoice_pdf` String, `account_name` String, `auto_advance` UInt8, `effective_at` DateTime, `subscription` String, `attempt_count` UInt8, `automatic_tax` String, `customer_name` String, `period_end_at` DateTime, `billing_reason` String, `customer_email` String, `ending_balance` Int64, `payment_intent` String, `account_country` String, `amount_shipping` Int64, `period_start_at` DateTime, `amount_remaining` Int64, `customer_address` String, `customer_tax_ids` String, `paid_out_of_band` UInt8, `payment_settings` String, `starting_balance` Int64, `collection_method` String, `default_tax_rates` String, `total_tax_amounts` String, `hosted_invoice_url` String, `status_transitions` String, `customer_tax_exempt` String, `total_excluding_tax` Int64, `subscription_details` String, `webhooks_delivered_at` DateTime, `subtotal_excluding_tax` Int64, `total_discount_amounts` String, `pre_payment_credit_notes_amount` Int64, `post_payment_credit_notes_amount` Int64') AS posthog_test_stripe_invoice
+ WHERE posthog_test_stripe_invoice.paid) AS invoice) AS revenue_analytics_revenue_item
+ GROUP BY customer_id) AS revenue_agg ON equals(revenue_analytics_customer.id, revenue_agg.customer_id)
+ LEFT JOIN (
+ SELECT `stripe.posthog_test.mrr_revenue_view`.customer_id AS customer_id, sum(`stripe.posthog_test.mrr_revenue_view`.mrr) AS mrr
+ FROM (
+ SELECT union.source_label AS source_label, union.customer_id AS customer_id, union.subscription_id AS subscription_id, argMax(union.amount, union.timestamp) AS mrr
+ FROM (
+ SELECT revenue_item.source_label AS source_label, revenue_item.customer_id AS customer_id, revenue_item.subscription_id AS subscription_id, toStartOfMonth(toTimeZone(revenue_item.timestamp, 'UTC')) AS timestamp, sum(revenue_item.amount) AS amount
+ FROM (
+ SELECT if(ifNull(greater(invoice.period_months, 1), 0), concat(ifNull(toString(invoice.invoice_item_id), ''), '_', ifNull(toString(invoice.month_index), '')), invoice.invoice_item_id) AS id, invoice.invoice_item_id AS invoice_item_id, 'stripe.posthog_test' AS source_label, addMonths(invoice.timestamp, invoice.month_index) AS timestamp, invoice.created_at AS created_at, ifNull(notEmpty(invoice.subscription_id), 0) AS is_recurring, invoice.product_id AS product_id, invoice.customer_id AS customer_id, NULL AS group_0_key, NULL AS group_1_key, NULL AS group_2_key, NULL AS group_3_key, NULL AS group_4_key, invoice.id AS invoice_id, invoice.subscription_id AS subscription_id, NULL AS session_id, NULL AS event_name, JSONExtractString(invoice.discount, 'coupon', 'name') AS coupon, JSONExtractString(invoice.discount, 'coupon', 'id') AS coupon_id, upper(invoice.currency) AS original_currency, accurateCastOrNull(invoice.amount_captured, 'Decimal64(10)') AS original_amount, in(original_currency, ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider, if(enable_currency_aware_divider, accurateCastOrNull(1, 'Decimal64(10)'), accurateCastOrNull(100, 'Decimal64(10)')) AS currency_aware_divider, divideDecimal(original_amount, currency_aware_divider) AS currency_aware_amount, 'GBP' AS currency, divideDecimal(if(equals(original_currency, currency), toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal128(0, 10), multiplyDecimal(divideDecimal(toDecimal128(currency_aware_amount, 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)) = 0, toDecimal128(1, 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', original_currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`, 'rate', currency, toDate(ifNull(timestamp, toDateTime(0, 'UTC'))), toDecimal64(0, 10))))), accurateCastOrNull(invoice.period_months, 'Decimal64(10)')) AS amount
+ FROM (
+ SELECT posthog_test_stripe_invoice.id AS id, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6, 'UTC') AS created_at, posthog_test_stripe_invoice.customer AS customer_id, posthog_test_stripe_invoice.subscription AS subscription_id, posthog_test_stripe_invoice.discount AS discount, arrayJoin(JSONExtractArrayRaw(assumeNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(posthog_test_stripe_invoice.lines, 'data'), ''), 'null'), '^"|"$', '')))) AS data, JSONExtractString(data, 'id') AS invoice_item_id, JSONExtractUInt(data, 'amount') AS amount_before_discount, coalesce(arraySum(arrayMap(x -> JSONExtractInt(x, 'amount'), JSONExtractArrayRaw(data, 'discount_amounts'))), 0) AS discount_amount, greatest(minus(amount_before_discount, discount_amount), 0) AS amount_captured, JSONExtractString(data, 'currency') AS currency, JSONExtractString(data, 'price', 'product') AS product_id, fromUnixTimestamp(JSONExtractUInt(data, 'period', 'start')) AS period_start, fromUnixTimestamp(JSONExtractUInt(data, 'period', 'end')) AS period_end, greatest(toInt16(round(divide(dateDiff('day', ifNull(period_start, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6, 'UTC')), ifNull(period_end, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6, 'UTC'))), 30.44))), 1) AS period_months, arrayJoin(range(0, period_months)) AS month_index, ifNull(period_start, parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6, 'UTC')) AS timestamp
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_invoices/posthog_test_stripe_invoice/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`id` String, `tax` Int64, `paid` UInt8, `lines` String, `total` Int64, `charge` String, `issuer` String, `number` String, `object` String, `status` String, `created` DateTime, `currency` String, `customer` String, `discount` String, `due_date` DateTime, `livemode` UInt8, `metadata` String, `subtotal` Int64, `attempted` UInt8, `discounts` String, `rendering` String, `amount_due` Int64, `amount_paid` Int64, `description` String, `invoice_pdf` String, `account_name` String, `auto_advance` UInt8, `effective_at` DateTime, `subscription` String, `attempt_count` UInt8, `automatic_tax` String, `customer_name` String, `period_end_at` DateTime, `billing_reason` String, `customer_email` String, `ending_balance` Int64, `payment_intent` String, `account_country` String, `amount_shipping` Int64, `period_start_at` DateTime, `amount_remaining` Int64, `customer_address` String, `customer_tax_ids` String, `paid_out_of_band` UInt8, `payment_settings` String, `starting_balance` Int64, `collection_method` String, `default_tax_rates` String, `total_tax_amounts` String, `hosted_invoice_url` String, `status_transitions` String, `customer_tax_exempt` String, `total_excluding_tax` Int64, `subscription_details` String, `webhooks_delivered_at` DateTime, `subtotal_excluding_tax` Int64, `total_discount_amounts` String, `pre_payment_credit_notes_amount` Int64, `post_payment_credit_notes_amount` Int64') AS posthog_test_stripe_invoice
+ WHERE posthog_test_stripe_invoice.paid) AS invoice) AS revenue_item WHERE and(revenue_item.is_recurring, isNotNull(revenue_item.subscription_id), ifNull(greaterOrEquals(timestamp, toStartOfMonth(addDays(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), -60))), 0), ifNull(lessOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), 0))
+ GROUP BY revenue_item.source_label, revenue_item.customer_id, revenue_item.subscription_id, timestamp
+ ORDER BY timestamp DESC
+ UNION ALL
+ SELECT `stripe.posthog_test.subscription_revenue_view`.source_label AS source_label, `stripe.posthog_test.subscription_revenue_view`.customer_id AS customer_id, `stripe.posthog_test.subscription_revenue_view`.id AS subscription_id, toTimeZone(`stripe.posthog_test.subscription_revenue_view`.ended_at, 'UTC') AS timestamp, accurateCastOrNull(0, 'Decimal64(10)') AS amount
+ FROM (
+ SELECT '' AS id, '' AS source_label, '' AS plan_id, '' AS product_id, '' AS customer_id, '' AS status, toDateTime64('1970-01-01 00:00:00.000000', 6, 'UTC') AS started_at, toDateTime64('1970-01-01 00:00:00.000000', 6, 'UTC') AS ended_at, '' AS metadata
+ WHERE 0) AS `stripe.posthog_test.subscription_revenue_view` WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfMonth(addDays(toDateTime64('explicit_redacted_timestamp', 6, 'UTC'), -60))), 0), ifNull(lessOrEquals(timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), 0))
+ ORDER BY timestamp DESC) AS
+ union
+ GROUP BY source_label, customer_id, subscription_id
+ ORDER BY customer_id ASC, subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`
+ GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons_revenue_analytics
+ LIMIT 100 SETTINGS format_csv_allow_double_quotes=1, readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0
+ '''
+# ---
+# name: TestPersonsRevenueAnalytics.test_revenue_aggregated_per_person_across_multiple_customers
+ '''
+ SELECT persons_revenue_analytics.person_id AS person_id,
+ persons_revenue_analytics.revenue AS revenue,
+ persons_revenue_analytics.mrr AS mrr
FROM
- (SELECT argMax(person.id, person.version) AS persons___id,
- person.id AS id
- FROM person
- WHERE and(equals(person.team_id, 99999), in(id,
- (SELECT where_optimization.id AS id
- FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), equals(where_optimization.id, toUUIDOrNull('00000000-0000-4000-8000-000000000000'))))))
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
- LEFT JOIN
(SELECT 99999 AS team_id,
person_id AS person_id,
sum(revenue) AS revenue,
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -2655,8 +3050,489 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))
- WHERE equals(persons.id, toUUIDOrNull('00000000-0000-4000-8000-000000000000'))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons_revenue_analytics
+ WHERE ifNull(equals(persons_revenue_analytics.person_id, toUUIDOrNull('00000000-0000-4000-8000-000000000000')), 0)
+ LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
+# name: TestPersonsRevenueAnalytics.test_revenue_aggregated_per_person_across_multiple_customers.1
+ '''
+ SELECT persons.id AS id,
+ persons__revenue_analytics.revenue AS `$virt_revenue`,
+ persons__revenue_analytics.mrr AS `$virt_mrr`
+ FROM (
+ SELECT argMax(person.id,
+ person.version) AS persons___id,
+ person.id AS id
+ FROM person
+ WHERE and(equals(person.team_id,
+ 99999), in(id, (
+ SELECT where_optimization.id AS id
+ FROM person AS where_optimization WHERE and(equals(where_optimization.team_id,
+ 99999), equals(where_optimization.id,
+ toUUIDOrNull('00000000-0000-4000-8000-000000000000'))))))
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted,
+ person.version), 0), less(argMax(toTimeZone(person.created_at,
+ 'UTC'), person.version), plus(now64(6,
+ 'UTC'), toIntervalDay(1))))) AS persons
+ LEFT JOIN (
+ SELECT 99999 AS team_id,
+ person_id AS person_id,
+ sum(revenue) AS revenue,
+ sum(mrr) AS mrr
+ FROM (
+ SELECT 99999 AS team_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id,
+ 'UUID') AS person_id,
+ coalesce(revenue_agg.revenue,
+ accurateCastOrNull(0,
+ 'Decimal64(10)')) AS revenue,
+ coalesce(mrr_agg.mrr,
+ accurateCastOrNull(0,
+ 'Decimal64(10)')) AS mrr
+ FROM (
+ SELECT inner.id AS id,
+ inner.source_label AS source_label,
+ inner.timestamp AS timestamp,
+ inner.name AS name,
+ inner.email AS email,
+ inner.phone AS phone,
+ inner.address AS address,
+ if(notEquals(JSONExtractString(inner.metadata,
+ 'posthog_person_distinct_id'), ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata,
+ '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata,
+ '{}'), k), JSONExtractKeys(ifNull(inner.metadata,
+ '{}')))), map('posthog_person_distinct_id_source',
+ 'customer'))), if(notEquals(inner.resolved_distinct_id,
+ ''), toJSONString(mapUpdate(mapFromArrays(JSONExtractKeys(ifNull(inner.metadata,
+ '{}')), arrayMap(k -> JSONExtractString(ifNull(inner.metadata,
+ '{}'), k), JSONExtractKeys(ifNull(inner.metadata,
+ '{}')))), map('posthog_person_distinct_id',
+ inner.resolved_distinct_id,
+ 'posthog_person_distinct_id_source',
+ inner.resolved_source))), inner.metadata)) AS metadata,
+ inner.country AS country,
+ inner.cohort AS cohort,
+ inner.initial_coupon AS initial_coupon,
+ inner.initial_coupon_id AS initial_coupon_id
+ FROM (
+ SELECT outer.id AS id,
+ 'stripe.posthog_test' AS source_label,
+ parseDateTime64BestEffortOrNull(toString(outer.created), 6,
+ 'UTC') AS timestamp,
+ outer.name AS name,
+ outer.email AS email,
+ outer.phone AS phone,
+ outer.address AS address,
+ outer.metadata AS metadata,
+ JSONExtractString(address,
+ 'country') AS country,
+ cohort_inner.cohort AS cohort,
+ cohort_inner.initial_coupon AS initial_coupon,
+ cohort_inner.initial_coupon_id AS initial_coupon_id,
+ ifNull(resolved.resolved_distinct_id,
+ '') AS resolved_distinct_id,
+ ifNull(resolved.resolved_source,
+ '') AS resolved_source
+ FROM (
+ SELECT *
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_customers/posthog_test_stripe_customer/*.csv',
+ 'object_storage_root_user',
+ 'object_storage_root_password',
+ 'CSVWithNames',
+ '`id` String, `name` String, `email` String, `phone` String, `address` String, `created` DateTime, `metadata` String')) AS outer
+ LEFT JOIN (
+ SELECT invoice.customer AS customer_id,
+ formatDateTime(toStartOfMonth(min(parseDateTime64BestEffortOrNull(toString(invoice.created), 6,
+ 'UTC'))), '%Y-%m') AS cohort,
+ argMin(JSONExtractString(invoice.discount,
+ 'coupon',
+ 'name'), parseDateTime64BestEffortOrNull(toString(invoice.created), 6,
+ 'UTC')) AS initial_coupon,
+ argMin(JSONExtractString(invoice.discount,
+ 'coupon',
+ 'id'), parseDateTime64BestEffortOrNull(toString(invoice.created), 6,
+ 'UTC')) AS initial_coupon_id
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_invoices/posthog_test_stripe_invoice/*.csv',
+ 'object_storage_root_user',
+ 'object_storage_root_password',
+ 'CSVWithNames',
+ '`id` String, `tax` Int64, `paid` UInt8, `lines` String, `total` Int64, `charge` String, `issuer` String, `number` String, `object` String, `status` String, `created` DateTime, `currency` String, `customer` String, `discount` String, `due_date` DateTime, `livemode` UInt8, `metadata` String, `subtotal` Int64, `attempted` UInt8, `discounts` String, `rendering` String, `amount_due` Int64, `amount_paid` Int64, `description` String, `invoice_pdf` String, `account_name` String, `auto_advance` UInt8, `effective_at` DateTime, `subscription` String, `attempt_count` UInt8, `automatic_tax` String, `customer_name` String, `period_end_at` DateTime, `billing_reason` String, `customer_email` String, `ending_balance` Int64, `payment_intent` String, `account_country` String, `amount_shipping` Int64, `period_start_at` DateTime, `amount_remaining` Int64, `customer_address` String, `customer_tax_ids` String, `paid_out_of_band` UInt8, `payment_settings` String, `starting_balance` Int64, `collection_method` String, `default_tax_rates` String, `total_tax_amounts` String, `hosted_invoice_url` String, `status_transitions` String, `customer_tax_exempt` String, `total_excluding_tax` Int64, `subscription_details` String, `webhooks_delivered_at` DateTime, `subtotal_excluding_tax` Int64, `total_discount_amounts` String, `pre_payment_credit_notes_amount` Int64, `post_payment_credit_notes_amount` Int64') AS invoice
+ GROUP BY invoice.customer) AS cohort_inner ON equals(cohort_inner.customer_id,
+ outer.id)
+ LEFT JOIN (
+ SELECT child_meta.customer_id AS customer_id,
+ argMax(child_meta.distinct_id,
+ child_meta.created_at) AS resolved_distinct_id,
+ argMax(child_meta.source_ref,
+ child_meta.created_at) AS resolved_source
+ FROM (
+ SELECT posthog_test_stripe_invoice.customer AS customer_id,
+ JSONExtractString(posthog_test_stripe_invoice.metadata,
+ 'posthog_person_distinct_id') AS distinct_id,
+ concat('invoice',
+ '::',
+ ifNull(toString(posthog_test_stripe_invoice.id), '')) AS source_ref,
+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,
+ 'UTC') AS created_at
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_invoices/posthog_test_stripe_invoice/*.csv',
+ 'object_storage_root_user',
+ 'object_storage_root_password',
+ 'CSVWithNames',
+ '`id` String, `tax` Int64, `paid` UInt8, `lines` String, `total` Int64, `charge` String, `issuer` String, `number` String, `object` String, `status` String, `created` DateTime, `currency` String, `customer` String, `discount` String, `due_date` DateTime, `livemode` UInt8, `metadata` String, `subtotal` Int64, `attempted` UInt8, `discounts` String, `rendering` String, `amount_due` Int64, `amount_paid` Int64, `description` String, `invoice_pdf` String, `account_name` String, `auto_advance` UInt8, `effective_at` DateTime, `subscription` String, `attempt_count` UInt8, `automatic_tax` String, `customer_name` String, `period_end_at` DateTime, `billing_reason` String, `customer_email` String, `ending_balance` Int64, `payment_intent` String, `account_country` String, `amount_shipping` Int64, `period_start_at` DateTime, `amount_remaining` Int64, `customer_address` String, `customer_tax_ids` String, `paid_out_of_band` UInt8, `payment_settings` String, `starting_balance` Int64, `collection_method` String, `default_tax_rates` String, `total_tax_amounts` String, `hosted_invoice_url` String, `status_transitions` String, `customer_tax_exempt` String, `total_excluding_tax` Int64, `subscription_details` String, `webhooks_delivered_at` DateTime, `subtotal_excluding_tax` Int64, `total_discount_amounts` String, `pre_payment_credit_notes_amount` Int64, `post_payment_credit_notes_amount` Int64') AS posthog_test_stripe_invoice
+ WHERE notEquals(JSONExtractString(posthog_test_stripe_invoice.metadata,
+ 'posthog_person_distinct_id'), '')) AS child_meta
+ GROUP BY child_meta.customer_id) AS resolved ON equals(resolved.customer_id,
+ outer.id)) AS inner
+ ORDER BY timestamp DESC
+ LIMIT 1 BY id) AS revenue_analytics_customer
+ LEFT JOIN (
+ SELECT persons.id AS id,
+ persons__pdi.distinct_id AS revenue_analytics_customer__persons___pdi___distinct_id
+ FROM (
+ SELECT argMax(person.id,
+ person.version) AS persons___id,
+ person.id AS id
+ FROM person
+ WHERE equals(person.team_id,
+ 99999)
+ GROUP BY person.id
+ HAVING and(equals(argMax(person.is_deleted,
+ person.version), 0), less(argMax(toTimeZone(person.created_at,
+ 'UTC'), person.version), plus(now64(6,
+ 'UTC'), toIntervalDay(1)))) SETTINGS optimize_aggregation_in_order=1) AS persons
+ LEFT JOIN (
+ SELECT argMax(person_distinct_id2.person_id,
+ person_distinct_id2.version) AS person_id,
+ person_distinct_id2.distinct_id AS distinct_id
+ FROM person_distinct_id2
+ WHERE equals(person_distinct_id2.team_id,
+ 99999)
+ GROUP BY person_distinct_id2.distinct_id
+ HAVING equals(argMax(person_distinct_id2.is_deleted,
+ person_distinct_id2.version), 0) SETTINGS optimize_aggregation_in_order=1) AS persons__pdi ON equals(persons.persons___id,
+ persons__pdi.person_id)) AS revenue_analytics_customer__persons ON equals(revenue_analytics_customer.id,
+ revenue_analytics_customer__persons.revenue_analytics_customer__persons___pdi___distinct_id)
+ LEFT JOIN (
+ SELECT revenue_analytics_revenue_item.customer_id AS customer_id,
+ sum(revenue_analytics_revenue_item.amount) AS revenue
+ FROM (
+ SELECT if(ifNull(greater(invoice.period_months,
+ 1), 0), concat(ifNull(toString(invoice.invoice_item_id), ''), '_',
+ ifNull(toString(invoice.month_index), '')), invoice.invoice_item_id) AS id,
+ invoice.invoice_item_id AS invoice_item_id,
+ 'stripe.posthog_test' AS source_label,
+ addMonths(invoice.timestamp,
+ invoice.month_index) AS timestamp,
+ invoice.created_at AS created_at,
+ ifNull(notEmpty(invoice.subscription_id), 0) AS is_recurring,
+ invoice.product_id AS product_id,
+ invoice.customer_id AS customer_id,
+ NULL AS group_0_key,
+ NULL AS group_1_key,
+ NULL AS group_2_key,
+ NULL AS group_3_key,
+ NULL AS group_4_key,
+ invoice.id AS invoice_id,
+ invoice.subscription_id AS subscription_id,
+ NULL AS session_id,
+ NULL AS event_name,
+ JSONExtractString(invoice.discount,
+ 'coupon',
+ 'name') AS coupon,
+ JSONExtractString(invoice.discount,
+ 'coupon',
+ 'id') AS coupon_id,
+ upper(invoice.currency) AS original_currency,
+ accurateCastOrNull(invoice.amount_captured,
+ 'Decimal64(10)') AS original_amount,
+ in(original_currency,
+ ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider,
+ if(enable_currency_aware_divider,
+ accurateCastOrNull(1,
+ 'Decimal64(10)'), accurateCastOrNull(100,
+ 'Decimal64(10)')) AS currency_aware_divider,
+ divideDecimal(original_amount,
+ currency_aware_divider) AS currency_aware_amount,
+ 'GBP' AS currency,
+ divideDecimal(if(equals(original_currency,
+ currency), toDecimal128(currency_aware_amount,
+ 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,
+ 'rate',
+ original_currency,
+ toDate(ifNull(timestamp, toDateTime(0,
+ 'UTC'))), toDecimal64(0,
+ 10)) = 0,
+ toDecimal128(0,
+ 10), multiplyDecimal(divideDecimal(toDecimal128(currency_aware_amount,
+ 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,
+ 'rate',
+ original_currency,
+ toDate(ifNull(timestamp, toDateTime(0,
+ 'UTC'))), toDecimal64(0,
+ 10)) = 0,
+ toDecimal128(1,
+ 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,
+ 'rate',
+ original_currency,
+ toDate(ifNull(timestamp, toDateTime(0,
+ 'UTC'))), toDecimal64(0,
+ 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,
+ 'rate',
+ currency,
+ toDate(ifNull(timestamp, toDateTime(0,
+ 'UTC'))), toDecimal64(0,
+ 10))))), accurateCastOrNull(invoice.period_months,
+ 'Decimal64(10)')) AS amount
+ FROM (
+ SELECT posthog_test_stripe_invoice.id AS id,
+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,
+ 'UTC') AS created_at,
+ posthog_test_stripe_invoice.customer AS customer_id,
+ posthog_test_stripe_invoice.subscription AS subscription_id,
+ posthog_test_stripe_invoice.discount AS discount,
+ arrayJoin(JSONExtractArrayRaw(assumeNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(posthog_test_stripe_invoice.lines,
+ 'data'), ''), 'null'), '^"|"$',
+ '')))) AS data,
+ JSONExtractString(data,
+ 'id') AS invoice_item_id,
+ JSONExtractUInt(data,
+ 'amount') AS amount_before_discount,
+ coalesce(arraySum(arrayMap(x -> JSONExtractInt(x,
+ 'amount'), JSONExtractArrayRaw(data,
+ 'discount_amounts'))), 0) AS discount_amount,
+ greatest(minus(amount_before_discount,
+ discount_amount), 0) AS amount_captured,
+ JSONExtractString(data,
+ 'currency') AS currency,
+ JSONExtractString(data,
+ 'price',
+ 'product') AS product_id,
+ fromUnixTimestamp(JSONExtractUInt(data,
+ 'period',
+ 'start')) AS period_start,
+ fromUnixTimestamp(JSONExtractUInt(data,
+ 'period',
+ 'end')) AS period_end,
+ greatest(toInt16(round(divide(dateDiff('day',
+ ifNull(period_start,
+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,
+ 'UTC')), ifNull(period_end,
+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,
+ 'UTC'))), 30.44))), 1) AS period_months,
+ arrayJoin(range(0,
+ period_months)) AS month_index,
+ ifNull(period_start,
+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,
+ 'UTC')) AS timestamp
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_invoices/posthog_test_stripe_invoice/*.csv',
+ 'object_storage_root_user',
+ 'object_storage_root_password',
+ 'CSVWithNames',
+ '`id` String, `tax` Int64, `paid` UInt8, `lines` String, `total` Int64, `charge` String, `issuer` String, `number` String, `object` String, `status` String, `created` DateTime, `currency` String, `customer` String, `discount` String, `due_date` DateTime, `livemode` UInt8, `metadata` String, `subtotal` Int64, `attempted` UInt8, `discounts` String, `rendering` String, `amount_due` Int64, `amount_paid` Int64, `description` String, `invoice_pdf` String, `account_name` String, `auto_advance` UInt8, `effective_at` DateTime, `subscription` String, `attempt_count` UInt8, `automatic_tax` String, `customer_name` String, `period_end_at` DateTime, `billing_reason` String, `customer_email` String, `ending_balance` Int64, `payment_intent` String, `account_country` String, `amount_shipping` Int64, `period_start_at` DateTime, `amount_remaining` Int64, `customer_address` String, `customer_tax_ids` String, `paid_out_of_band` UInt8, `payment_settings` String, `starting_balance` Int64, `collection_method` String, `default_tax_rates` String, `total_tax_amounts` String, `hosted_invoice_url` String, `status_transitions` String, `customer_tax_exempt` String, `total_excluding_tax` Int64, `subscription_details` String, `webhooks_delivered_at` DateTime, `subtotal_excluding_tax` Int64, `total_discount_amounts` String, `pre_payment_credit_notes_amount` Int64, `post_payment_credit_notes_amount` Int64') AS posthog_test_stripe_invoice
+ WHERE posthog_test_stripe_invoice.paid) AS invoice) AS revenue_analytics_revenue_item
+ GROUP BY customer_id) AS revenue_agg ON equals(revenue_analytics_customer.id,
+ revenue_agg.customer_id)
+ LEFT JOIN (
+ SELECT `stripe.posthog_test.mrr_revenue_view`.customer_id AS customer_id,
+ sum(`stripe.posthog_test.mrr_revenue_view`.mrr) AS mrr
+ FROM (
+ SELECT union.source_label AS source_label,
+ union.customer_id AS customer_id,
+ union.subscription_id AS subscription_id,
+ argMax(union.amount,
+ union.timestamp) AS mrr
+ FROM (
+ SELECT revenue_item.source_label AS source_label,
+ revenue_item.customer_id AS customer_id,
+ revenue_item.subscription_id AS subscription_id,
+ toStartOfMonth(toTimeZone(revenue_item.timestamp,
+ 'UTC')) AS timestamp,
+ sum(revenue_item.amount) AS amount
+ FROM (
+ SELECT if(ifNull(greater(invoice.period_months,
+ 1), 0), concat(ifNull(toString(invoice.invoice_item_id), ''), '_',
+ ifNull(toString(invoice.month_index), '')), invoice.invoice_item_id) AS id,
+ invoice.invoice_item_id AS invoice_item_id,
+ 'stripe.posthog_test' AS source_label,
+ addMonths(invoice.timestamp,
+ invoice.month_index) AS timestamp,
+ invoice.created_at AS created_at,
+ ifNull(notEmpty(invoice.subscription_id), 0) AS is_recurring,
+ invoice.product_id AS product_id,
+ invoice.customer_id AS customer_id,
+ NULL AS group_0_key,
+ NULL AS group_1_key,
+ NULL AS group_2_key,
+ NULL AS group_3_key,
+ NULL AS group_4_key,
+ invoice.id AS invoice_id,
+ invoice.subscription_id AS subscription_id,
+ NULL AS session_id,
+ NULL AS event_name,
+ JSONExtractString(invoice.discount,
+ 'coupon',
+ 'name') AS coupon,
+ JSONExtractString(invoice.discount,
+ 'coupon',
+ 'id') AS coupon_id,
+ upper(invoice.currency) AS original_currency,
+ accurateCastOrNull(invoice.amount_captured,
+ 'Decimal64(10)') AS original_amount,
+ in(original_currency,
+ ['BIF', 'CLP', 'DJF', 'GNF', 'JPY', 'KMF', 'KRW', 'MGA', 'PYG', 'RWF', 'UGX', 'VND', 'VUV', 'XAF', 'XOF', 'XPF']) AS enable_currency_aware_divider,
+ if(enable_currency_aware_divider,
+ accurateCastOrNull(1,
+ 'Decimal64(10)'), accurateCastOrNull(100,
+ 'Decimal64(10)')) AS currency_aware_divider,
+ divideDecimal(original_amount,
+ currency_aware_divider) AS currency_aware_amount,
+ 'GBP' AS currency,
+ divideDecimal(if(equals(original_currency,
+ currency), toDecimal128(currency_aware_amount,
+ 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,
+ 'rate',
+ original_currency,
+ toDate(ifNull(timestamp, toDateTime(0,
+ 'UTC'))), toDecimal64(0,
+ 10)) = 0,
+ toDecimal128(0,
+ 10), multiplyDecimal(divideDecimal(toDecimal128(currency_aware_amount,
+ 10), if(dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,
+ 'rate',
+ original_currency,
+ toDate(ifNull(timestamp, toDateTime(0,
+ 'UTC'))), toDecimal64(0,
+ 10)) = 0,
+ toDecimal128(1,
+ 10), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,
+ 'rate',
+ original_currency,
+ toDate(ifNull(timestamp, toDateTime(0,
+ 'UTC'))), toDecimal64(0,
+ 10)))), dictGetOrDefault(`posthog_test`.`exchange_rate_dict`,
+ 'rate',
+ currency,
+ toDate(ifNull(timestamp, toDateTime(0,
+ 'UTC'))), toDecimal64(0,
+ 10))))), accurateCastOrNull(invoice.period_months,
+ 'Decimal64(10)')) AS amount
+ FROM (
+ SELECT posthog_test_stripe_invoice.id AS id,
+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,
+ 'UTC') AS created_at,
+ posthog_test_stripe_invoice.customer AS customer_id,
+ posthog_test_stripe_invoice.subscription AS subscription_id,
+ posthog_test_stripe_invoice.discount AS discount,
+ arrayJoin(JSONExtractArrayRaw(assumeNotNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(posthog_test_stripe_invoice.lines,
+ 'data'), ''), 'null'), '^"|"$',
+ '')))) AS data,
+ JSONExtractString(data,
+ 'id') AS invoice_item_id,
+ JSONExtractUInt(data,
+ 'amount') AS amount_before_discount,
+ coalesce(arraySum(arrayMap(x -> JSONExtractInt(x,
+ 'amount'), JSONExtractArrayRaw(data,
+ 'discount_amounts'))), 0) AS discount_amount,
+ greatest(minus(amount_before_discount,
+ discount_amount), 0) AS amount_captured,
+ JSONExtractString(data,
+ 'currency') AS currency,
+ JSONExtractString(data,
+ 'price',
+ 'product') AS product_id,
+ fromUnixTimestamp(JSONExtractUInt(data,
+ 'period',
+ 'start')) AS period_start,
+ fromUnixTimestamp(JSONExtractUInt(data,
+ 'period',
+ 'end')) AS period_end,
+ greatest(toInt16(round(divide(dateDiff('day',
+ ifNull(period_start,
+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,
+ 'UTC')), ifNull(period_end,
+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,
+ 'UTC'))), 30.44))), 1) AS period_months,
+ arrayJoin(range(0,
+ period_months)) AS month_index,
+ ifNull(period_start,
+ parseDateTime64BestEffortOrNull(toString(posthog_test_stripe_invoice.created), 6,
+ 'UTC')) AS timestamp
+ FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-posthog.revenue_analytics.insights_query_runner.stripe_invoices/posthog_test_stripe_invoice/*.csv',
+ 'object_storage_root_user',
+ 'object_storage_root_password',
+ 'CSVWithNames',
+ '`id` String, `tax` Int64, `paid` UInt8, `lines` String, `total` Int64, `charge` String, `issuer` String, `number` String, `object` String, `status` String, `created` DateTime, `currency` String, `customer` String, `discount` String, `due_date` DateTime, `livemode` UInt8, `metadata` String, `subtotal` Int64, `attempted` UInt8, `discounts` String, `rendering` String, `amount_due` Int64, `amount_paid` Int64, `description` String, `invoice_pdf` String, `account_name` String, `auto_advance` UInt8, `effective_at` DateTime, `subscription` String, `attempt_count` UInt8, `automatic_tax` String, `customer_name` String, `period_end_at` DateTime, `billing_reason` String, `customer_email` String, `ending_balance` Int64, `payment_intent` String, `account_country` String, `amount_shipping` Int64, `period_start_at` DateTime, `amount_remaining` Int64, `customer_address` String, `customer_tax_ids` String, `paid_out_of_band` UInt8, `payment_settings` String, `starting_balance` Int64, `collection_method` String, `default_tax_rates` String, `total_tax_amounts` String, `hosted_invoice_url` String, `status_transitions` String, `customer_tax_exempt` String, `total_excluding_tax` Int64, `subscription_details` String, `webhooks_delivered_at` DateTime, `subtotal_excluding_tax` Int64, `total_discount_amounts` String, `pre_payment_credit_notes_amount` Int64, `post_payment_credit_notes_amount` Int64') AS posthog_test_stripe_invoice
+ WHERE posthog_test_stripe_invoice.paid) AS invoice) AS revenue_item WHERE and(revenue_item.is_recurring,
+ isNotNull(revenue_item.subscription_id), ifNull(greaterOrEquals(timestamp, toStartOfMonth(addDays(toDateTime64('2025-05-30 00:00:00.000000',
+ 6,
+ 'UTC'), -60))), 0), ifNull(lessOrEquals(timestamp, toDateTime64('2025-05-30 00:00:00.000000',
+ 6,
+ 'UTC')), 0))
+ GROUP BY revenue_item.source_label,
+ revenue_item.customer_id,
+ revenue_item.subscription_id, timestamp
+ ORDER BY timestamp DESC
+ UNION ALL
+ SELECT `stripe.posthog_test.subscription_revenue_view`.source_label AS source_label,
+ `stripe.posthog_test.subscription_revenue_view`.customer_id AS customer_id,
+ `stripe.posthog_test.subscription_revenue_view`.id AS subscription_id,
+ toTimeZone(`stripe.posthog_test.subscription_revenue_view`.ended_at,
+ 'UTC') AS timestamp,
+ accurateCastOrNull(0,
+ 'Decimal64(10)') AS amount
+ FROM (
+ SELECT '' AS id,
+ '' AS source_label,
+ '' AS plan_id,
+ '' AS product_id,
+ '' AS customer_id,
+ '' AS status,
+ toDateTime64('1970-01-01 00:00:00.000000',
+ 6,
+ 'UTC') AS started_at,
+ toDateTime64('1970-01-01 00:00:00.000000',
+ 6,
+ 'UTC') AS ended_at,
+ '' AS metadata
+ WHERE 0) AS `stripe.posthog_test.subscription_revenue_view` WHERE and(ifNull(greaterOrEquals(timestamp, toStartOfMonth(addDays(toDateTime64('2025-05-30 00:00:00.000000',
+ 6,
+ 'UTC'), -60))), 0), ifNull(lessOrEquals(timestamp, toDateTime64('2025-05-30 00:00:00.000000',
+ 6,
+ 'UTC')), 0))
+ ORDER BY timestamp DESC) AS
+ union
+ GROUP BY source_label,
+ customer_id,
+ subscription_id
+ ORDER BY customer_id ASC,
+ subscription_id ASC) AS `stripe.posthog_test.mrr_revenue_view`
+ GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id,
+ mrr_agg.customer_id))
+ WHERE ifNull(notEquals(person_id,
+ accurateCastOrNull('00000000-0000-0000-0000-000000000000',
+ 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000',
+ 'UUID')))
+ GROUP BY person_id) AS persons__revenue_analytics ON equals(persons.persons___id,
+ persons__revenue_analytics.person_id)
+ WHERE equals(persons.id,
+ toUUIDOrNull('00000000-0000-4000-8000-000000000000'))
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
max_execution_time=60,
@@ -2718,7 +3594,7 @@
LEFT JOIN (
SELECT 99999 AS team_id, person_id AS person_id, sum(revenue) AS revenue, sum(mrr) AS mrr
FROM (
- SELECT 99999 AS team_id, revenue_analytics_customer.id AS person_id, coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue, coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
+ SELECT 99999 AS team_id, accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id, coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue, coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM (
SELECT toString(persons.id) AS id, 'revenue_analytics.events.purchase' AS source_label, persons.created_at AS timestamp, persons.properties___name AS name, persons.properties___email AS email, persons.properties___phone AS phone, persons.properties___address AS address, persons.properties___metadata AS metadata, persons.`properties___$geoip_country_name` AS country, formatDateTime(toStartOfMonth(persons.created_at), '%Y-%m') AS cohort, NULL AS initial_coupon, NULL AS initial_coupon_id
FROM (
@@ -2790,7 +3666,9 @@
GROUP BY source_label, customer_id, subscription_id
ORDER BY customer_id ASC, subscription_id ASC) AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS e__pdi__person__revenue_analytics ON equals(toString(e__pdi__person.e__pdi__person___id), toString(e__pdi__person__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS e__pdi__person__revenue_analytics ON equals(e__pdi__person.e__pdi__person___id, e__pdi__person__revenue_analytics.person_id)
WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
GROUP BY day_start, breakdown_value_1)
GROUP BY day_start, breakdown_value_1
@@ -2850,7 +3728,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -2997,7 +3875,9 @@
ORDER BY customer_id ASC,
subscription_id ASC) AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS e__poe__revenue_analytics ON equals(toString(e.person_id), toString(e__poe__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS e__poe__revenue_analytics ON equals(e.person_id, e__poe__revenue_analytics.person_id)
WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
GROUP BY day_start,
breakdown_value_1)
@@ -3064,7 +3944,7 @@
LEFT JOIN (
SELECT 99999 AS team_id, person_id AS person_id, sum(revenue) AS revenue, sum(mrr) AS mrr
FROM (
- SELECT 99999 AS team_id, revenue_analytics_customer.id AS person_id, coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue, coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
+ SELECT 99999 AS team_id, accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id, coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue, coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM (
SELECT toString(persons.id) AS id, 'revenue_analytics.events.purchase' AS source_label, persons.created_at AS timestamp, persons.properties___name AS name, persons.properties___email AS email, persons.properties___phone AS phone, persons.properties___address AS address, persons.properties___metadata AS metadata, persons.`properties___$geoip_country_name` AS country, formatDateTime(toStartOfMonth(persons.created_at), '%Y-%m') AS cohort, NULL AS initial_coupon, NULL AS initial_coupon_id
FROM (
@@ -3130,7 +4010,9 @@
GROUP BY source_label, customer_id, subscription_id
ORDER BY customer_id ASC, subscription_id ASC) AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS e__poe__revenue_analytics ON equals(toString(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)), toString(e__poe__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS e__poe__revenue_analytics ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__poe__revenue_analytics.person_id)
WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
GROUP BY day_start, breakdown_value_1)
GROUP BY day_start, breakdown_value_1
@@ -3189,7 +4071,7 @@
LEFT JOIN (
SELECT 99999 AS team_id, person_id AS person_id, sum(revenue) AS revenue, sum(mrr) AS mrr
FROM (
- SELECT 99999 AS team_id, revenue_analytics_customer.id AS person_id, coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue, coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
+ SELECT 99999 AS team_id, accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id, coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue, coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM (
SELECT toString(persons.id) AS id, 'revenue_analytics.events.purchase' AS source_label, persons.created_at AS timestamp, persons.properties___name AS name, persons.properties___email AS email, persons.properties___phone AS phone, persons.properties___address AS address, persons.properties___metadata AS metadata, persons.`properties___$geoip_country_name` AS country, formatDateTime(toStartOfMonth(persons.created_at), '%Y-%m') AS cohort, NULL AS initial_coupon, NULL AS initial_coupon_id
FROM (
@@ -3261,7 +4143,9 @@
GROUP BY source_label, customer_id, subscription_id
ORDER BY customer_id ASC, subscription_id ASC) AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS e__person__revenue_analytics ON equals(toString(e__person.e__person___id), toString(e__person__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS e__person__revenue_analytics ON equals(e__person.e__person___id, e__person__revenue_analytics.person_id)
WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
GROUP BY day_start, breakdown_value_1)
GROUP BY day_start, breakdown_value_1
@@ -3274,6 +4158,31 @@
LIMIT 50000 SETTINGS readonly=2, max_execution_time=60, allow_experimental_object_type=1, max_ast_elements=4000000, max_expanded_ast_elements=4000000, max_bytes_before_external_group_by=0, transform_null_in=1, optimize_min_equality_disjunction_chain_length=4294967295, optimize_rewrite_aggregate_function_with_if=0, optimize_min_inequality_conjunction_chain_length=4294967295, allow_experimental_join_condition=1, use_hive_partitioning=0
'''
# ---
+# name: TestPersonsRevenueAnalytics.test_warehouse_join_named_persons_pointing_elsewhere_is_ignored
+ '''
+ SELECT persons_revenue_analytics.person_id AS person_id,
+ persons_revenue_analytics.revenue AS revenue
+ FROM
+ (SELECT 99999 AS team_id,
+ toUUIDOrNull('00000000-0000-0000-0000-000000000000') AS person_id,
+ 0 AS revenue,
+ 0 AS mrr
+ WHERE 0) AS persons_revenue_analytics
+ LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
+ readonly=2,
+ max_execution_time=60,
+ allow_experimental_object_type=1,
+ max_ast_elements=4000000,
+ max_expanded_ast_elements=4000000,
+ max_bytes_before_external_group_by=0,
+ transform_null_in=1,
+ optimize_min_equality_disjunction_chain_length=4294967295,
+ optimize_rewrite_aggregate_function_with_if=0,
+ optimize_min_inequality_conjunction_chain_length=4294967295,
+ allow_experimental_join_condition=1,
+ use_hive_partitioning=0
+ '''
+# ---
# name: TestPersonsRevenueAnalyticsManagedViewsets.test_get_revenue_for_events
'''
SELECT persons__revenue_analytics.revenue AS revenue,
@@ -3285,7 +4194,7 @@
WHERE and(equals(person.team_id, 99999), in(id,
(SELECT where_optimization.id AS id
FROM person AS where_optimization
- WHERE and(equals(where_optimization.team_id, 99999), equals(where_optimization.id, '00000000-0000-0000-0000-000000000000')))))
+ WHERE and(equals(where_optimization.team_id, 99999), equals(where_optimization.id, '0193a0b1-2c3d-4e5f-8899-aabbccddeeff')))))
GROUP BY person.id
HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))) AS persons
LEFT JOIN
@@ -3295,7 +4204,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -3311,8 +4220,10 @@
sum(`revenue_analytics.events.purchase.mrr_events_revenue_view`.mrr) AS mrr
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-revenue_analytics_events_purchase_mrr_events_revenue_view/revenue_analytics.events.purchase.mrr_events_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))
- WHERE equals(persons.id, '00000000-0000-0000-0000-000000000000')
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons__revenue_analytics ON equals(persons.persons___id, persons__revenue_analytics.person_id)
+ WHERE equals(persons.id, '0193a0b1-2c3d-4e5f-8899-aabbccddeeff')
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
max_execution_time=60,
@@ -3346,7 +4257,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -3379,7 +4290,9 @@
sum(`stripe.posthog_test.mrr_revenue_view`.mrr) AS mrr
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-stripe_posthog_test_mrr_revenue_view/stripe.posthog_test.mrr_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons__revenue_analytics ON equals(persons.persons___id, persons__revenue_analytics.person_id)
ORDER BY persons.id ASC
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
@@ -3414,7 +4327,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -3447,7 +4360,9 @@
sum(`stripe.posthog_test.mrr_revenue_view`.mrr) AS mrr
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-stripe_posthog_test_mrr_revenue_view/stripe.posthog_test.mrr_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS persons__revenue_analytics ON equals(toString(persons.persons___id), toString(persons__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS persons__revenue_analytics ON equals(persons.persons___id, persons__revenue_analytics.person_id)
ORDER BY persons.id ASC
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
readonly=2,
@@ -3476,7 +4391,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -3492,6 +4407,8 @@
sum(`revenue_analytics.events.purchase.mrr_events_revenue_view`.mrr) AS mrr
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-revenue_analytics_events_purchase_mrr_events_revenue_view/revenue_analytics.events.purchase.mrr_events_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
GROUP BY person_id) AS persons_revenue_analytics
ORDER BY persons_revenue_analytics.person_id ASC
LIMIT 100 SETTINGS format_csv_allow_double_quotes=1,
@@ -3521,7 +4438,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer__persons.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer__persons.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -3554,6 +4471,8 @@
sum(`stripe.posthog_test.mrr_revenue_view`.mrr) AS mrr
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-stripe_posthog_test_mrr_revenue_view/stripe.posthog_test.mrr_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `stripe.posthog_test.mrr_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
GROUP BY person_id) AS persons_revenue_analytics
ORDER BY persons_revenue_analytics.mrr DESC,
persons_revenue_analytics.revenue DESC
@@ -3629,7 +4548,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -3645,7 +4564,9 @@
sum(`revenue_analytics.events.purchase.mrr_events_revenue_view`.mrr) AS mrr
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-revenue_analytics_events_purchase_mrr_events_revenue_view/revenue_analytics.events.purchase.mrr_events_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS e__pdi__person__revenue_analytics ON equals(toString(e__pdi__person.e__pdi__person___id), toString(e__pdi__person__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS e__pdi__person__revenue_analytics ON equals(e__pdi__person.e__pdi__person___id, e__pdi__person__revenue_analytics.person_id)
WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
GROUP BY day_start,
breakdown_value_1)
@@ -3770,7 +4691,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -3786,7 +4707,9 @@
sum(`revenue_analytics.events.purchase.mrr_events_revenue_view`.mrr) AS mrr
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-revenue_analytics_events_purchase_mrr_events_revenue_view/revenue_analytics.events.purchase.mrr_events_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS e__poe__revenue_analytics ON equals(toString(e.person_id), toString(e__poe__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS e__poe__revenue_analytics ON equals(e.person_id, e__poe__revenue_analytics.person_id)
WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
GROUP BY day_start,
breakdown_value_1)
@@ -3918,7 +4841,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -3934,7 +4857,9 @@
sum(`revenue_analytics.events.purchase.mrr_events_revenue_view`.mrr) AS mrr
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-revenue_analytics_events_purchase_mrr_events_revenue_view/revenue_analytics.events.purchase.mrr_events_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS e__poe__revenue_analytics ON equals(toString(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id)), toString(e__poe__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS e__poe__revenue_analytics ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__poe__revenue_analytics.person_id)
WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
GROUP BY day_start,
breakdown_value_1)
@@ -4073,7 +4998,7 @@
sum(mrr) AS mrr
FROM
(SELECT 99999 AS team_id,
- revenue_analytics_customer.id AS person_id,
+ accurateCastOrNull(revenue_analytics_customer.id, 'UUID') AS person_id,
coalesce(revenue_agg.revenue, accurateCastOrNull(0, 'Decimal64(10)')) AS revenue,
coalesce(mrr_agg.mrr, accurateCastOrNull(0, 'Decimal64(10)')) AS mrr
FROM
@@ -4089,7 +5014,9 @@
sum(`revenue_analytics.events.purchase.mrr_events_revenue_view`.mrr) AS mrr
FROM s3('http://host.docker.internal:19000/posthog/test_storage_bucket-revenue_analytics_events_purchase_mrr_events_revenue_view/revenue_analytics.events.purchase.mrr_events_revenue_view/*.csv', 'object_storage_root_user', 'object_storage_root_password', 'CSVWithNames', '`mrr` Nullable(Decimal64(10)), `customer_id` Nullable(String), `source_label` Nullable(String), `subscription_id` Nullable(String)') AS `revenue_analytics.events.purchase.mrr_events_revenue_view`
GROUP BY customer_id) AS mrr_agg ON equals(revenue_analytics_customer.id, mrr_agg.customer_id))
- GROUP BY person_id) AS e__person__revenue_analytics ON equals(toString(e__person.e__person___id), toString(e__person__revenue_analytics.person_id))
+ WHERE ifNull(notEquals(person_id, accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')), isNotNull(person_id)
+ or isNotNull(accurateCastOrNull('00000000-0000-0000-0000-000000000000', 'UUID')))
+ GROUP BY person_id) AS e__person__revenue_analytics ON equals(e__person.e__person___id, e__person__revenue_analytics.person_id)
WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2025-05-29 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2025-05-30 23:59:59', 'UTC'))), equals(e.event, '$pageview'))
GROUP BY day_start,
breakdown_value_1)
diff --git a/posthog/hogql/database/schema/test/test_persons_revenue_analytics.py b/posthog/hogql/database/schema/test/test_persons_revenue_analytics.py
index 16ef6c050272..d24b4b5e609b 100644
--- a/posthog/hogql/database/schema/test/test_persons_revenue_analytics.py
+++ b/posthog/hogql/database/schema/test/test_persons_revenue_analytics.py
@@ -1,7 +1,9 @@
from decimal import Decimal
+from uuid import UUID
from freezegun import freeze_time
from posthog.test.base import _create_event, _create_person, snapshot_clickhouse_queries
+from unittest.mock import patch
from parameterized import parameterized
@@ -17,6 +19,7 @@ from posthog.schema import (
)
from posthog.hogql import ast
+from posthog.hogql.database.schema import persons_revenue_analytics
from posthog.hogql.database.schema.test.base import RevenueAnalyticsManagedViewsetsTestMixin, RevenueAnalyticsTestBase
from posthog.hogql.parser import parse_select
from posthog.hogql.query import execute_hogql_query
@@ -28,6 +31,10 @@ from products.revenue_analytics.backend.views.schemas.customer import SCHEMA
class TestPersonsRevenueAnalyticsMixin(RevenueAnalyticsTestBase):
+ # The base default is the all-zeros UUID, which this table drops as the unattributable key a
+ # LEFT JOIN miss produces. Real person UUIDs are never all-zeros, so use one that isn't.
+ PERSON_ID = "0193a0b1-2c3d-4e5f-8899-aabbccddeeff"
+
def setup_events(self):
_create_person(
uuid=self.PERSON_ID,
@@ -331,6 +338,122 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
)
self.assertEqual(persons_results.results, [(person.uuid, expected_revenue, expected_mrr)])
+ def test_revenue_aggregated_per_person_across_event_and_warehouse_sources(self):
+ self.setup_schema_sources()
+
+ self.setup_events()
+
+ self.team.revenue_analytics_config.events = [
+ RevenueAnalyticsEventItem(
+ eventName=self.PURCHASE_EVENT_NAME,
+ revenueProperty=self.REVENUE_PROPERTY,
+ revenueCurrencyProperty=RevenueCurrencyPropertyConfig(static="USD"),
+ currencyAwareDecimal=True,
+ )
+ ]
+ self.team.revenue_analytics_config.save()
+ self.team.save()
+
+ # Both source kinds are configured, so the two legs of the UNION ALL must agree on `person_id`
+ warehouse_person = _create_person(team_id=self.team.pk, distinct_ids=["cus_1"])
+
+ # `cus_2` through `cus_6` match no person, so they carry the all-zeros UUID and are dropped.
+ # Only the two attributable rows remain, one from each leg.
+ with freeze_time(self.QUERY_TIMESTAMP):
+ results = execute_hogql_query(
+ parse_select("SELECT person_id, revenue, mrr FROM persons_revenue_analytics"),
+ self.team,
+ user=self.user,
+ modifiers=self.MODIFIERS,
+ )
+
+ self.assertEqual(
+ sorted(results.results),
+ sorted(
+ [
+ (warehouse_person.uuid, Decimal("283.8496260553"), Decimal("22.9631447238")),
+ (UUID(self.PERSON_ID), Decimal("279.28474"), Decimal("0")),
+ ]
+ ),
+ )
+
+ def test_warehouse_join_named_persons_pointing_elsewhere_is_ignored(self):
+ self.create_sources()
+ self.team.base_currency = CurrencyCode.GBP.value
+ self.team.save()
+
+ # `field_name` is user-controlled, so a join can be called `persons` while pointing anywhere.
+ # Reading `id` off that table casts to NULL, which would pool every customer's revenue into
+ # one row keyed on nothing. The source is skipped instead.
+ DataWarehouseJoin.objects.create(
+ team=self.team,
+ source_table_name=f"stripe.posthog_test.{SCHEMA.source_suffix}",
+ source_table_key="id",
+ joining_table_name="posthog_test_stripe_customer",
+ joining_table_key="id",
+ field_name="persons",
+ )
+
+ with freeze_time(self.QUERY_TIMESTAMP), patch.object(persons_revenue_analytics, "logger") as mock_logger:
+ results = execute_hogql_query(
+ parse_select("SELECT person_id, revenue FROM persons_revenue_analytics"),
+ self.team,
+ user=self.user,
+ modifiers=self.MODIFIERS,
+ )
+
+ self.assertEqual(results.results, [])
+
+ # Dropping the source is silent in the results, so the warning is the only way to tell
+ # this apart from the source genuinely earning nothing.
+ mock_logger.warning.assert_called_once()
+ event, kwargs = mock_logger.warning.call_args[0][0], mock_logger.warning.call_args[1]
+ self.assertEqual(event, "persons_revenue_analytics_skipped_source")
+ self.assertEqual(kwargs["team_id"], self.team.pk)
+
+ @parameterized.expand(["events", "warehouse", "none"])
+ def test_person_id_joins_directly_against_persons_id(self, source_kind: str):
+ # `person_id` is the documented join target for `persons.id`. The event leg reaches it through
+ # `toString(persons.id)`, so it is the leg that fails with `NO_COMMON_TYPE` when the column is
+ # not cast back to UUID. The warehouse leg already holds a UUID and passes either way, so both
+ # kinds are covered to stop one of them regressing alone. `none` covers the empty-table branch,
+ # which is most projects: the join has to return no rows there rather than fail on the types.
+ # `none` configures no source at all, so the table falls to its empty branch
+ expected_rows: list[tuple] = []
+ if source_kind == "events":
+ self.setup_events()
+ self.team.revenue_analytics_config.events = [
+ RevenueAnalyticsEventItem(
+ eventName=self.PURCHASE_EVENT_NAME,
+ revenueProperty=self.REVENUE_PROPERTY,
+ revenueCurrencyProperty=RevenueCurrencyPropertyConfig(static="USD"),
+ currencyAwareDecimal=True,
+ )
+ ]
+ self.team.revenue_analytics_config.save()
+ self.team.save()
+ expected_rows = [(UUID(self.PERSON_ID), Decimal("350.42"))]
+ elif source_kind == "warehouse":
+ self.setup_schema_sources()
+ person = _create_person(team_id=self.team.pk, distinct_ids=["cus_1"])
+ expected_rows = [(person.uuid, Decimal("283.8496260553"))]
+
+ with freeze_time(self.QUERY_TIMESTAMP):
+ results = execute_hogql_query(
+ parse_select(
+ """
+ SELECT persons.id, revenue.revenue
+ FROM persons
+ JOIN persons_revenue_analytics AS revenue ON persons.id = revenue.person_id
+ """
+ ),
+ self.team,
+ user=self.user,
+ modifiers=self.MODIFIERS,
+ )
+
+ self.assertEqual(results.results, expected_rows)
+
def test_query_revenue_analytics_table_sources(self):
self.setup_schema_sources()
self.join.source_table_key = "id"
@@ -392,7 +515,7 @@ class TestPersonsRevenueAnalytics(TestPersonsRevenueAnalyticsMixin):
# Total revenue = 100.42 + 250.42 = 350.84, MRR = 250.42 (only the recurring event)
self.assertEqual(
results.results,
- [(self.PERSON_ID, Decimal("350.84"), Decimal("250.42"))],
+ [(UUID(self.PERSON_ID), Decimal("350.84"), Decimal("250.42"))],
)
@parameterized.expand([e.value for e in PersonsOnEventsMode])
@@ -491,7 +614,7 @@ class TestPersonsRevenueAnalyticsManagedViewsets(
# MRR is calculated from recurring events (those with subscription_id)
self.assertEqual(
results.results,
- [(self.PERSON_ID, Decimal("350.84"), Decimal("250.42"))],
+ [(UUID(self.PERSON_ID), Decimal("350.84"), Decimal("250.42"))],
)
def test_query_revenue_analytics_table_sources(self):