Skip to content

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

feat(insights): default trends property aggregation to median (#68755)

Thomas Obermüllerc0eb128cd87a
diff --git a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
index 86a76d2e07c1..06c6ad58910d 100644
--- a/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
+++ b/frontend/src/queries/nodes/InsightViz/InsightVizDisplay.tsx
@@ -21,6 +21,10 @@ import {
InsightTimeoutState,
InsightValidationError,
} from 'scenes/insights/EmptyStates'
+import {
+ SUPPORTED_PROPERTY_MATH_FOR_HISTOGRAM_BREAKDOWN,
+ isPropertyValueMath,
+} from 'scenes/insights/filters/ActionFilter/ActionFilterRow/mathUtils'
import { InsightAIAnalysis } from 'scenes/insights/InsightAIAnalysis'
import { insightDataLogic } from 'scenes/insights/insightDataLogic'
import { insightLogic } from 'scenes/insights/insightLogic'
@@ -46,7 +50,14 @@ import { SceneSection } from '~/layout/scenes/components/SceneSection'
import { InsightVizNode, TrendsQuery } from '~/queries/schema/schema-general'
import { QueryContext } from '~/queries/types'
import { shouldQueryBeAsync } from '~/queries/utils'
-import { ChartDisplayType, ExporterFormat, FunnelVizType, InsightLogicProps, InsightType } from '~/types'
+import {
+ ChartDisplayType,
+ ExporterFormat,
+ FunnelVizType,
+ InsightLogicProps,
+ InsightType,
+ PropertyMathType,
+} from '~/types'
import { InsightDisplayConfig } from './InsightDisplayConfig'
import { InsightResultMetadata } from './InsightResultMetadata'
@@ -215,18 +226,38 @@ export function InsightVizDisplay({
Reset unsupported settings
</LemonButton>
) : undefined
+ const useAverageCta =
+ validationErrorCode === 'property_math_unsupported_with_histogram_breakdown' ? (
+ <LemonButton
+ type="primary"
+ loading={insightDataLoading}
+ onClick={() =>
+ updateQuerySource({
+ series: ((series as TrendsQuery['series']) ?? []).map((s) =>
+ isPropertyValueMath(s.math) &&
+ !SUPPORTED_PROPERTY_MATH_FOR_HISTOGRAM_BREAKDOWN.has(s.math)
+ ? { ...s, math: PropertyMathType.Average }
+ : s
+ ),
+ } as Partial<TrendsQuery>)
+ }
+ >
+ Use average instead
+ </LemonButton>
+ ) : undefined
+ const cta = resetCta ?? useAverageCta
return (
<InsightValidationError
query={query}
detail={validationError}
onRetry={
- resetCta
+ cta
? undefined
: () => {
loadData(query && shouldQueryBeAsync(query) ? 'force_async' : 'force_blocking')
}
}
- cta={resetCta}
+ cta={cta}
/>
)
}
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/mathUtils.test.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/mathUtils.test.ts
new file mode 100644
index 000000000000..c20f8b392dbe
--- /dev/null
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/mathUtils.test.ts
@@ -0,0 +1,35 @@
+import { PropertyMathType } from '~/types'
+
+import { getDefaultPropertyMathType } from './mathUtils'
+
+describe('getDefaultPropertyMathType', () => {
+ test.each([
+ ['defaults to median', undefined, undefined, false, PropertyMathType.Median],
+ // median can't be rolled up across histogram buckets, so the default must stay backend-safe
+ ['falls back to average for histogram breakdowns', undefined, undefined, true, PropertyMathType.Average],
+ ['keeps the currently selected property math', PropertyMathType.P90, undefined, false, PropertyMathType.P90],
+ [
+ 'uses the first allowed property math type',
+ undefined,
+ [PropertyMathType.Sum, PropertyMathType.Average],
+ false,
+ PropertyMathType.Sum,
+ ],
+ [
+ 'skips allowed types unsupported for histogram breakdowns',
+ undefined,
+ [PropertyMathType.Median, PropertyMathType.Sum],
+ true,
+ PropertyMathType.Sum,
+ ],
+ [
+ 'falls back to average when no allowed type supports histogram breakdowns',
+ undefined,
+ [PropertyMathType.Median, PropertyMathType.P90],
+ true,
+ PropertyMathType.Average,
+ ],
+ ])('%s', (_name, math, allowedMathTypes, isHistogramBreakdown, expected) => {
+ expect(getDefaultPropertyMathType(math, allowedMathTypes, isHistogramBreakdown)).toBe(expected)
+ })
+})
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/mathUtils.ts b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/mathUtils.ts
index 456579a0451b..b060f89732bd 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/mathUtils.ts
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/mathUtils.ts
@@ -21,16 +21,24 @@ export function isCountPerActorMath(math: string | undefined): math is CountPerA
export function getDefaultPropertyMathType(
math: string | undefined,
- allowedMathTypes: readonly string[] | undefined
+ allowedMathTypes: readonly string[] | undefined,
+ isHistogramBreakdown?: boolean
): PropertyMathType {
+ // Median isn't supported when rolling up histogram buckets, so fall back to average there
+ const defaultMathType = isHistogramBreakdown ? PropertyMathType.Average : PropertyMathType.Median
if (isPropertyValueMath(math)) {
return math
}
if (allowedMathTypes?.length) {
- const propertyMathTypes = allowedMathTypes.filter(isPropertyValueMath)
- return (propertyMathTypes[0] as PropertyMathType) || PropertyMathType.Average
+ let propertyMathTypes = allowedMathTypes.filter(isPropertyValueMath)
+ if (isHistogramBreakdown) {
+ propertyMathTypes = propertyMathTypes.filter((mathType) =>
+ SUPPORTED_PROPERTY_MATH_FOR_HISTOGRAM_BREAKDOWN.has(mathType)
+ )
+ }
+ return propertyMathTypes[0] || defaultMathType
}
- return PropertyMathType.Average
+ return defaultMathType
}
export function getDefaultMathHogQLExpression(insightType?: InsightType): string {
diff --git a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx
index a932c421d801..f4e69e6dd1cd 100644
--- a/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx
+++ b/frontend/src/scenes/insights/filters/ActionFilter/ActionFilterRow/useMathSelectorOptions.tsx
@@ -82,8 +82,13 @@ export function useMathSelectorOptions({
} = useValues(mathsLogic)
const [propertyMathTypeShown, setPropertyMathTypeShown] = useState<PropertyMathType>(
- getDefaultPropertyMathType(math, allowedMathTypes)
+ getDefaultPropertyMathType(math, allowedMathTypes, !!isHistogramBreakdown)
)
+ // state initializes once at mount, so clamp at render in case a histogram breakdown was enabled afterwards
+ const effectivePropertyMathTypeShown =
+ isHistogramBreakdown && !SUPPORTED_PROPERTY_MATH_FOR_HISTOGRAM_BREAKDOWN.has(propertyMathTypeShown)
+ ? getDefaultPropertyMathType(undefined, allowedMathTypes, true)
+ : propertyMathTypeShown
const [countPerActorMathTypeShown, setCountPerActorMathTypeShown] = useState<CountPerActorMathType>(
isCountPerActorMath(math) ? math : CountPerActorMathType.Average
@@ -215,13 +220,13 @@ export function useMathSelectorOptions({
if (shouldShowPropertyValue) {
options.push({
- value: propertyMathTypeShown,
- label: `Property value ${PROPERTY_MATH_DEFINITIONS[propertyMathTypeShown].shortName}`,
+ value: effectivePropertyMathTypeShown,
+ label: `Property value ${PROPERTY_MATH_DEFINITIONS[effectivePropertyMathTypeShown].shortName}`,
labelInMenu: (
<div className="flex items-center gap-2">
<span>Property value</span>
<LemonSelect
- value={propertyMathTypeShown}
+ value={effectivePropertyMathTypeShown}
onSelect={(value) => {
setPropertyMathTypeShown(value as PropertyMathType)
onMathSelect(index, value)
diff --git a/posthog/hogql_queries/insights/trends/test/test_trend_validation_rules.py b/posthog/hogql_queries/insights/trends/test/test_trend_validation_rules.py
index 72cb1aa1c2dd..ef134469dc3f 100644
--- a/posthog/hogql_queries/insights/trends/test/test_trend_validation_rules.py
+++ b/posthog/hogql_queries/insights/trends/test/test_trend_validation_rules.py
@@ -11,10 +11,14 @@ from posthog.schema import (
DataWarehouseNode,
EventsNode,
MultipleBreakdownType,
+ PropertyMathType,
TrendsQuery,
)
-from posthog.hogql_queries.insights.trends.trend_validation_rules import ValidateDataWarehouseBreakdown
+from posthog.hogql_queries.insights.trends.trend_validation_rules import (
+ DisallowUnsupportedPropertyMathForHistogramBreakdown,
+ ValidateDataWarehouseBreakdown,
+)
from posthog.hogql_queries.validation.validation import QueryValidationContext
@@ -251,3 +255,79 @@ class TestValidateDataWarehouseBreakdown(BaseTest):
context.exception.get_codes(),
["data_warehouse_series_unsupported_breakdown"],
)
+
+
+class TestDisallowUnsupportedPropertyMathForHistogramBreakdown(BaseTest):
+ def _context(self, query: TrendsQuery) -> QueryValidationContext[TrendsQuery]:
+ runner = MagicMock(query=query, team=self.team, user=None)
+ return QueryValidationContext(query=query, team=self.team, user=None, runner=runner)
+
+ @parameterized.expand(
+ [
+ ("no_breakdown", PropertyMathType.MEDIAN, None),
+ ("breakdown_without_bins", PropertyMathType.MEDIAN, BreakdownFilter(breakdown="prop")),
+ (
+ "supported_math_with_bins",
+ PropertyMathType.AVG,
+ BreakdownFilter(breakdown="prop", breakdown_histogram_bin_count=10),
+ ),
+ (
+ "multi_breakdown_without_bins",
+ PropertyMathType.P90,
+ BreakdownFilter(breakdowns=[Breakdown(property="prop")]),
+ ),
+ ]
+ )
+ def test_allows_supported_combinations(
+ self, _name: str, math: PropertyMathType, breakdown_filter: BreakdownFilter | None
+ ) -> None:
+ query = TrendsQuery(
+ series=[EventsNode(event="$pageview", math=math, math_property="prop")],
+ breakdownFilter=breakdown_filter,
+ )
+
+ DisallowUnsupportedPropertyMathForHistogramBreakdown().validate(self._context(query))
+
+ @parameterized.expand(
+ [
+ (
+ "single_breakdown",
+ PropertyMathType.MEDIAN,
+ BreakdownFilter(breakdown="prop", breakdown_histogram_bin_count=10),
+ ),
+ (
+ "multi_breakdown",
+ PropertyMathType.P90,
+ BreakdownFilter(breakdowns=[Breakdown(property="prop", histogram_bin_count=10)]),
+ ),
+ ]
+ )
+ def test_disallows_unsupported_math_with_histogram_breakdown(
+ self, _name: str, math: PropertyMathType, breakdown_filter: BreakdownFilter
+ ) -> None:
+ query = TrendsQuery(
+ series=[EventsNode(event="$pageview", math=math, math_property="prop")],
+ breakdownFilter=breakdown_filter,
+ )
+
+ with self.assertRaises(ValidationError) as context:
+ DisallowUnsupportedPropertyMathForHistogramBreakdown().validate(self._context(query))
+
+ self.assertEqual(
+ context.exception.get_codes(),
+ ["property_math_unsupported_with_histogram_breakdown"],
+ )
+
+ def test_error_message_names_the_unsupported_math_types(self) -> None:
+ query = TrendsQuery(
+ series=[
+ EventsNode(event="$pageview", math=PropertyMathType.MEDIAN, math_property="prop"),
+ EventsNode(event="$pageview", math=PropertyMathType.SUM, math_property="prop"),
+ ],
+ breakdownFilter=BreakdownFilter(breakdown="prop", breakdown_histogram_bin_count=10),
+ )
+
+ with self.assertRaises(ValidationError) as context:
+ DisallowUnsupportedPropertyMathForHistogramBreakdown().validate(self._context(query))
+
+ self.assertIn("Median is not supported", str(context.exception))
diff --git a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
index 6dccc185cb4a..71db6a7b6209 100644
--- a/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/test/test_trends_query_runner.py
@@ -2119,8 +2119,8 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
assert results_by_breakdown["[2,3.01]"]["data"] == [0, 200.0, 0]
- def test_trends_breakdown_histogram_with_unsupported_math_type_raises_error(self):
- with pytest.raises(ValueError) as exc_info:
+ def test_trends_breakdown_histogram_with_unsupported_math_type_raises_validation_error(self):
+ with pytest.raises(DRFValidationError) as exc_info:
self._run_trends_query(
"2020-01-11",
"2020-01-13",
@@ -2133,7 +2133,7 @@ class TestTrendsQueryRunner(ClickhouseTestMixin, APIBaseTest):
breakdown_histogram_bin_count=2,
),
)
- assert "is not supported with histogram breakdowns" in str(exc_info.value)
+ assert exc_info.value.get_codes() == ["property_math_unsupported_with_histogram_breakdown"]
@parameterized.expand(
[
diff --git a/posthog/hogql_queries/insights/trends/trend_validation_rules.py b/posthog/hogql_queries/insights/trends/trend_validation_rules.py
index 07258e62f9c4..16dfe7f3ac33 100644
--- a/posthog/hogql_queries/insights/trends/trend_validation_rules.py
+++ b/posthog/hogql_queries/insights/trends/trend_validation_rules.py
@@ -1,7 +1,8 @@
from rest_framework.exceptions import ValidationError
-from posthog.schema import BreakdownType, MultipleBreakdownType, TrendsQuery
+from posthog.schema import BreakdownType, MultipleBreakdownType, PropertyMathType, TrendsQuery
+from posthog.hogql_queries.insights.trends.aggregation_operations import SUPPORTED_PROPERTY_MATH_FOR_HISTOGRAM_BREAKDOWN
from posthog.hogql_queries.insights.utils.breakdowns import (
has_breakdown_filter,
has_multi_breakdown,
@@ -47,3 +48,42 @@ class ValidateDataWarehouseBreakdown:
f"Event based breakdowns are not supported for {insight_name} with a data warehouse series.",
code=self.code,
)
+
+
+class DisallowUnsupportedPropertyMathForHistogramBreakdown:
+ """Median and percentile property math can't be merged when rolling up histogram breakdown buckets."""
+
+ code = "property_math_unsupported_with_histogram_breakdown"
+
+ def validate(self, context: QueryValidationContext[TrendsQuery]) -> None:
+ breakdown_filter = context.query.breakdownFilter
+ if not has_breakdown_filter(breakdown_filter):
+ return
+ assert breakdown_filter is not None # type checking
+
+ if has_multi_breakdown(breakdown_filter):
+ assert breakdown_filter.breakdowns is not None # type checking
+ has_histogram = any(breakdown.histogram_bin_count is not None for breakdown in breakdown_filter.breakdowns)
+ else:
+ has_histogram = breakdown_filter.breakdown_histogram_bin_count is not None
+ if not has_histogram:
+ return
+
+ unsupported_math_types = sorted(
+ {
+ PropertyMathType(series.math)
+ for series in context.query.series
+ if series.math in set(PropertyMathType)
+ and series.math not in SUPPORTED_PROPERTY_MATH_FOR_HISTOGRAM_BREAKDOWN
+ }
+ )
+ if not unsupported_math_types:
+ return
+
+ names = " and ".join(unsupported_math_types)
+ verb = "is" if len(unsupported_math_types) == 1 else "are"
+ raise ValidationError(
+ f"{names.capitalize()} {verb} not supported when breakdown values are grouped into bins. "
+ "Use average instead, or turn off binning on the breakdown.",
+ code=self.code,
+ )
diff --git a/posthog/hogql_queries/insights/trends/trends_query_runner.py b/posthog/hogql_queries/insights/trends/trends_query_runner.py
index 562bff9fde99..225b1788543a 100644
--- a/posthog/hogql_queries/insights/trends/trends_query_runner.py
+++ b/posthog/hogql_queries/insights/trends/trends_query_runner.py
@@ -57,7 +57,10 @@ from posthog.clickhouse import query_tagging
from posthog.clickhouse.query_tagging import QueryTags
from posthog.hogql_queries.insights.trends.display import TrendsDisplay
from posthog.hogql_queries.insights.trends.series_with_extras import SeriesWithExtras
-from posthog.hogql_queries.insights.trends.trend_validation_rules import ValidateDataWarehouseBreakdown
+from posthog.hogql_queries.insights.trends.trend_validation_rules import (
+ DisallowUnsupportedPropertyMathForHistogramBreakdown,
+ ValidateDataWarehouseBreakdown,
+)
from posthog.hogql_queries.insights.trends.trends_actors_query_builder import TrendsActorsQueryBuilder
from posthog.hogql_queries.insights.trends.trends_query_builder import TrendsQueryBuilder
from posthog.hogql_queries.insights.utils.breakdowns import (
@@ -151,6 +154,7 @@ class TrendsQueryRunner(AnalyticsQueryRunner[TrendsQueryResponse]):
RequireAtLeastOneSeries(),
DisallowUnsupportedDataWarehouseSettings(),
ValidateDataWarehouseBreakdown(),
+ DisallowUnsupportedPropertyMathForHistogramBreakdown(),
)
def _refresh_frequency(self):
diff --git a/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambr b/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambr
index c3eef83c2e4e..394be1f1a878 100644
--- a/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambr
+++ b/posthog/hogql_queries/test/__snapshots__/test_sessions_query_runner.ambr
@@ -270,78 +270,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestSessionsQueryRunner.test_basic_sessions_query_minus_utc
- '''
- SELECT tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) AS `tuple(session_id, distinct_id, $start_timestamp, $end_timestamp, $session_duration, $entry_current_url, $end_current_url, $pageview_count, $autocapture_count, $screen_count, $is_bounce)`
- FROM
- (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'America/Phoenix')) AS `$start_timestamp`,
- max(toTimeZone(raw_sessions.max_timestamp, 'America/Phoenix')) AS `$end_timestamp`,
- dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'America/Phoenix')), max(toTimeZone(raw_sessions.max_timestamp, 'America/Phoenix'))) AS `$session_duration`,
- nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '') AS `$entry_current_url`,
- nullIf(nullIf(argMaxMerge(raw_sessions.end_url), 'null'), '') AS `$end_current_url`,
- uniqMerge(raw_sessions.pageview_uniq) AS `$pageview_count`,
- uniqMerge(raw_sessions.autocapture_uniq) AS `$autocapture_count`,
- uniqMerge(raw_sessions.screen_uniq) AS `$screen_count`,
- if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'America/Phoenix')), max(toTimeZone(raw_sessions.max_timestamp, 'America/Phoenix'))), 10)))) AS `$is_bounce`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-01 07:00:05.000000', 6, 'America/Phoenix'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-01 00:00:00.000000', 6, 'America/Phoenix'), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS sessions
- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 07:00:05.000000', 6, 'America/Phoenix')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'America/Phoenix')), 0))
- ORDER BY tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) ASC
- LIMIT 101
- OFFSET 0 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: TestSessionsQueryRunner.test_basic_sessions_query_plus_utc
- '''
- SELECT tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) AS `tuple(session_id, distinct_id, $start_timestamp, $end_timestamp, $session_duration, $entry_current_url, $end_current_url, $pageview_count, $autocapture_count, $screen_count, $is_bounce)`
- FROM
- (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'Asia/Tokyo')) AS `$start_timestamp`,
- max(toTimeZone(raw_sessions.max_timestamp, 'Asia/Tokyo')) AS `$end_timestamp`,
- dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'Asia/Tokyo')), max(toTimeZone(raw_sessions.max_timestamp, 'Asia/Tokyo'))) AS `$session_duration`,
- nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '') AS `$entry_current_url`,
- nullIf(nullIf(argMaxMerge(raw_sessions.end_url), 'null'), '') AS `$end_current_url`,
- uniqMerge(raw_sessions.pageview_uniq) AS `$pageview_count`,
- uniqMerge(raw_sessions.autocapture_uniq) AS `$autocapture_count`,
- uniqMerge(raw_sessions.screen_uniq) AS `$screen_count`,
- if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'Asia/Tokyo')), max(toTimeZone(raw_sessions.max_timestamp, 'Asia/Tokyo'))), 10)))) AS `$is_bounce`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-01 23:00:05.000000', 6, 'Asia/Tokyo'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-01 00:00:00.000000', 6, 'Asia/Tokyo'), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS sessions
- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-01 23:00:05.000000', 6, 'Asia/Tokyo')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-01 00:00:00.000000', 6, 'Asia/Tokyo')), 0))
- ORDER BY tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) ASC
- LIMIT 101
- OFFSET 0 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: TestSessionsQueryRunner.test_filter_by_event_properties_without_event_name
'''
SELECT sessions.session_id AS session_id
@@ -1120,78 +1048,6 @@
use_hive_partitioning=0
'''
# ---
-# name: TestSessionsQueryRunner.test_sessions_date_range_minus_utc
- '''
- SELECT tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) AS `tuple(session_id, distinct_id, $start_timestamp, $end_timestamp, $session_duration, $entry_current_url, $end_current_url, $pageview_count, $autocapture_count, $screen_count, $is_bounce)`
- FROM
- (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'America/Phoenix')) AS `$start_timestamp`,
- max(toTimeZone(raw_sessions.max_timestamp, 'America/Phoenix')) AS `$end_timestamp`,
- dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'America/Phoenix')), max(toTimeZone(raw_sessions.max_timestamp, 'America/Phoenix'))) AS `$session_duration`,
- nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '') AS `$entry_current_url`,
- nullIf(nullIf(argMaxMerge(raw_sessions.end_url), 'null'), '') AS `$end_current_url`,
- uniqMerge(raw_sessions.pageview_uniq) AS `$pageview_count`,
- uniqMerge(raw_sessions.autocapture_uniq) AS `$autocapture_count`,
- uniqMerge(raw_sessions.screen_uniq) AS `$screen_count`,
- if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'America/Phoenix')), max(toTimeZone(raw_sessions.max_timestamp, 'America/Phoenix'))), 10)))) AS `$is_bounce`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-03 16:59:59.000000', 6, 'America/Phoenix'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-02 00:00:00.000000', 6, 'America/Phoenix'), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS sessions
- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-03 16:59:59.000000', 6, 'America/Phoenix')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-02 00:00:00.000000', 6, 'America/Phoenix')), 0))
- ORDER BY tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) ASC
- LIMIT 101
- OFFSET 0 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: TestSessionsQueryRunner.test_sessions_date_range_plus_utc
- '''
- SELECT tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) AS `tuple(session_id, distinct_id, $start_timestamp, $end_timestamp, $session_duration, $entry_current_url, $end_current_url, $pageview_count, $autocapture_count, $screen_count, $is_bounce)`
- FROM
- (SELECT toString(reinterpretAsUUID(bitOr(bitShiftLeft(raw_sessions.session_id_v7, 64), bitShiftRight(raw_sessions.session_id_v7, 64)))) AS session_id,
- nullIf(argMaxMerge(raw_sessions.distinct_id), 'null') AS distinct_id,
- min(toTimeZone(raw_sessions.min_timestamp, 'Asia/Tokyo')) AS `$start_timestamp`,
- max(toTimeZone(raw_sessions.max_timestamp, 'Asia/Tokyo')) AS `$end_timestamp`,
- dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'Asia/Tokyo')), max(toTimeZone(raw_sessions.max_timestamp, 'Asia/Tokyo'))) AS `$session_duration`,
- nullIf(nullIf(argMinMerge(raw_sessions.entry_url), 'null'), '') AS `$entry_current_url`,
- nullIf(nullIf(argMaxMerge(raw_sessions.end_url), 'null'), '') AS `$end_current_url`,
- uniqMerge(raw_sessions.pageview_uniq) AS `$pageview_count`,
- uniqMerge(raw_sessions.autocapture_uniq) AS `$autocapture_count`,
- uniqMerge(raw_sessions.screen_uniq) AS `$screen_count`,
- if(ifNull(equals(uniqMerge(raw_sessions.pageview_uniq), 0), 0), NULL, not(or(ifNull(greater(uniqMerge(raw_sessions.pageview_uniq), 1), 0), ifNull(greater(uniqMerge(raw_sessions.autocapture_uniq), 0), 0), greaterOrEquals(dateDiff('second', min(toTimeZone(raw_sessions.min_timestamp, 'Asia/Tokyo')), max(toTimeZone(raw_sessions.max_timestamp, 'Asia/Tokyo'))), 10)))) AS `$is_bounce`,
- raw_sessions.session_id_v7 AS session_id_v7
- FROM raw_sessions
- WHERE and(equals(raw_sessions.team_id, 99999), lessOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), plus(toDateTime64('2024-01-04 08:59:59.000000', 6, 'Asia/Tokyo'), toIntervalDay(3))), greaterOrEquals(fromUnixTimestamp(intDiv(toUInt64(bitShiftRight(raw_sessions.session_id_v7, 80)), 1000)), minus(toDateTime64('2024-01-02 00:00:00.000000', 6, 'Asia/Tokyo'), toIntervalDay(3))))
- GROUP BY raw_sessions.session_id_v7) AS sessions
- WHERE and(ifNull(less(sessions.`$start_timestamp`, toDateTime64('2024-01-04 08:59:59.000000', 6, 'Asia/Tokyo')), 0), ifNull(greater(sessions.`$start_timestamp`, toDateTime64('2024-01-02 00:00:00.000000', 6, 'Asia/Tokyo')), 0))
- ORDER BY tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) ASC
- LIMIT 101
- OFFSET 0 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: TestSessionsQueryRunner.test_sessions_limit_and_offset
'''
SELECT tuple(sessions.session_id, sessions.distinct_id, sessions.`$start_timestamp`, sessions.`$end_timestamp`, sessions.`$session_duration`, sessions.`$entry_current_url`, sessions.`$end_current_url`, sessions.`$pageview_count`, sessions.`$autocapture_count`, sessions.`$screen_count`, sessions.`$is_bounce`) AS `tuple(session_id, distinct_id, $start_timestamp, $end_timestamp, $session_duration, $entry_current_url, $end_current_url, $pageview_count, $autocapture_count, $screen_count, $is_bounce)`