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.

perf(marketing-analytics): run compare periods via UNION ALL pivot (#66181)

Javier Bahamondes0c6dfabc244b
diff --git a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_marketing_analytics_table_query_runner_compare.ambr b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_marketing_analytics_table_query_runner_compare.ambr
index 00b3e7d71649..88ba3d3335da 100644
--- a/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_marketing_analytics_table_query_runner_compare.ambr
+++ b/products/marketing_analytics/backend/hogql_queries/__snapshots__/test_marketing_analytics_table_query_runner_compare.ambr
@@ -58,313 +58,354 @@
'''
SELECT
- tuple(current_period.ID, previous_period.ID) AS ID,
- tuple(current_period.Campaign, previous_period.Campaign) AS Campaign,
- tuple(current_period.Source, previous_period.Source) AS Source,
- tuple(current_period.Cost, previous_period.Cost) AS Cost,
- tuple(current_period.Clicks, previous_period.Clicks) AS Clicks,
- tuple(current_period.Impressions, previous_period.Impressions) AS Impressions,
- tuple(current_period.CPC, previous_period.CPC) AS CPC,
- tuple(current_period.CTR, previous_period.CTR) AS CTR,
- tuple(current_period.`Reported Conversions`, previous_period.`Reported Conversions`) AS `Reported Conversions`,
- tuple(current_period.`Reported Conversion Value`, previous_period.`Reported Conversion Value`) AS `Reported Conversion Value`,
- tuple(current_period.`Reported ROAS`, previous_period.`Reported ROAS`) AS `Reported ROAS`,
- tuple(current_period.`Cost per Reported Conversions`, previous_period.`Cost per Reported Conversions`) AS `Cost per Reported Conversions`,
- tuple(current_period.`Sign Up Conversions`, previous_period.`Sign Up Conversions`) AS `Sign Up Conversions`,
- tuple(current_period.`Cost per Sign Up Conversions`, previous_period.`Cost per Sign Up Conversions`) AS `Cost per Sign Up Conversions`
+ tuple(anyIf(combined.ID, equals(combined._period, 'current')), anyIf(combined.ID, equals(combined._period, 'previous'))) AS ID,
+ tuple(anyIf(combined.Campaign, equals(combined._period, 'current')), anyIf(combined.Campaign, equals(combined._period, 'previous'))) AS Campaign,
+ tuple(anyIf(combined.Source, equals(combined._period, 'current')), anyIf(combined.Source, equals(combined._period, 'previous'))) AS Source,
+ tuple(anyIf(combined.Cost, equals(combined._period, 'current')), anyIf(combined.Cost, equals(combined._period, 'previous'))) AS Cost,
+ tuple(anyIf(combined.Clicks, equals(combined._period, 'current')), anyIf(combined.Clicks, equals(combined._period, 'previous'))) AS Clicks,
+ tuple(anyIf(combined.Impressions, equals(combined._period, 'current')), anyIf(combined.Impressions, equals(combined._period, 'previous'))) AS Impressions,
+ tuple(anyIf(combined.CPC, equals(combined._period, 'current')), anyIf(combined.CPC, equals(combined._period, 'previous'))) AS CPC,
+ tuple(anyIf(combined.CTR, equals(combined._period, 'current')), anyIf(combined.CTR, equals(combined._period, 'previous'))) AS CTR,
+ tuple(anyIf(combined.`Reported Conversions`, equals(combined._period, 'current')), anyIf(combined.`Reported Conversions`, equals(combined._period, 'previous'))) AS `Reported Conversions`,
+ tuple(anyIf(combined.`Reported Conversion Value`, equals(combined._period, 'current')), anyIf(combined.`Reported Conversion Value`, equals(combined._period, 'previous'))) AS `Reported Conversion Value`,
+ tuple(anyIf(combined.`Reported ROAS`, equals(combined._period, 'current')), anyIf(combined.`Reported ROAS`, equals(combined._period, 'previous'))) AS `Reported ROAS`,
+ tuple(anyIf(combined.`Cost per Reported Conversions`, equals(combined._period, 'current')), anyIf(combined.`Cost per Reported Conversions`, equals(combined._period, 'previous'))) AS `Cost per Reported Conversions`,
+ tuple(anyIf(combined.`Sign Up Conversions`, equals(combined._period, 'current')), anyIf(combined.`Sign Up Conversions`, equals(combined._period, 'previous'))) AS `Sign Up Conversions`,
+ tuple(anyIf(combined.`Cost per Sign Up Conversions`, equals(combined._period, 'current')), anyIf(combined.`Cost per Sign Up Conversions`, equals(combined._period, 'previous'))) AS `Cost per Sign Up Conversions`
FROM
- (WITH
- campaign_costs AS (
- SELECT
- campaign,
- id,
- source,
- any(match_key) AS match_key,
- sum(ifNull(toFloat(cost), 0)) AS total_cost,
- sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
- sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
- sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
- sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
- FROM
- (
+ (
+ SELECT
+ 'current' AS _period,
+ ID,
+ Campaign,
+ Source,
+ Cost,
+ Clicks,
+ Impressions,
+ CPC,
+ CTR,
+ `Reported Conversions`,
+ `Reported Conversion Value`,
+ `Reported ROAS`,
+ `Cost per Reported Conversions`,
+ `Sign Up Conversions`,
+ `Cost per Sign Up Conversions`
+ FROM
+ (WITH
+ campaign_costs AS (
SELECT
- toString(campaign1) AS match_key,
- toString(campaign1) AS campaign,
- toString(campaign1) AS id,
- toString('Facebook Ads') AS source,
- toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
- toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
- toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
- toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
- 0 AS reported_conversion_value
+ campaign,
+ id,
+ source,
+ any(match_key) AS match_key,
+ sum(ifNull(toFloat(cost), 0)) AS total_cost,
+ sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
+ sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
+ sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
+ sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
FROM
- `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
- WHERE
- and(greaterOrEquals(toDateTime(date1), toDateTime('2024-11-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-12-31 23:59:59'))))
- GROUP BY
- campaign,
- id,
- source),
- ucg AS (
- SELECT
- conv.campaign AS campaign,
- conv.id AS id,
- conv.source AS source,
- conv.campaign AS match_key,
- sum(conv.conversion_0) AS conversion_0
- FROM
- (
+ (
+ SELECT
+ toString(campaign1) AS match_key,
+ toString(campaign1) AS campaign,
+ toString(campaign1) AS id,
+ toString('Facebook Ads') AS source,
+ toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
+ toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
+ toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
+ toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
+ 0 AS reported_conversion_value
+ FROM
+ `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
+ WHERE
+ and(greaterOrEquals(toDateTime(date1), toDateTime('2024-11-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-12-31 23:59:59'))))
+ GROUP BY
+ campaign,
+ id,
+ source),
+ ucg AS (
SELECT
- if(notEmpty(campaign_name), campaign_name, 'organic') AS campaign,
- if(notEmpty(campaign_id), campaign_id, '-') AS id,
- if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['microsoft', 'msads', 'bing_video']), 'bing', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['facebook', 'instagram', 'messenger', 'fb', 'whatsapp', 'audience_network', 'facebook_marketplace', 'threads']), 'meta', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['li']), 'linkedin', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['adwords', 'youtube', 'display', 'gmail', 'google_maps', 'google_play', 'google_discover', 'admob', 'waze']), 'google', if(notEmpty(source_name), source_name, 'organic'))))) AS source,
- count() AS conversion_0
+ conv.campaign AS campaign,
+ conv.id AS id,
+ conv.source AS source,
+ conv.campaign AS match_key,
+ sum(conv.conversion_0) AS conversion_0
FROM
(
SELECT
- person_id,
- if(notEmpty(conversion_campaign), conversion_campaign, if(notEmpty(fallback_campaign), fallback_campaign, '')) AS campaign_name,
- if(notEmpty(conversion_source), conversion_source, if(notEmpty(fallback_source), fallback_source, '')) AS source_name,
- if(notEmpty(conversion_medium), conversion_medium, if(notEmpty(fallback_medium), fallback_medium, '')) AS medium_name,
- if(notEmpty(conversion_content), conversion_content, if(notEmpty(fallback_content), fallback_content, '')) AS content_name,
- if(notEmpty(conversion_term), conversion_term, if(notEmpty(fallback_term), fallback_term, '')) AS term_name,
- if(notEmpty(conversion_referring_domain), conversion_referring_domain, if(notEmpty(fallback_referring_domain), fallback_referring_domain, '')) AS referring_domain_name,
- if(notEmpty(conversion_gclid), conversion_gclid, if(notEmpty(fallback_gclid), fallback_gclid, '')) AS gclid_name,
- if(notEmpty(conversion_fbclid), conversion_fbclid, if(notEmpty(fallback_fbclid), fallback_fbclid, '')) AS fbclid_name,
- if(notEmpty(conversion_gad_source), conversion_gad_source, if(notEmpty(fallback_gad_source), fallback_gad_source, '')) AS gad_source_name,
- '-' AS campaign_id,
- 1 AS conversion_value
+ if(notEmpty(campaign_name), campaign_name, 'organic') AS campaign,
+ if(notEmpty(campaign_id), campaign_id, '-') AS id,
+ if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['microsoft', 'msads', 'bing_video']), 'bing', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['facebook', 'instagram', 'messenger', 'fb', 'whatsapp', 'audience_network', 'facebook_marketplace', 'threads']), 'meta', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['li']), 'linkedin', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['adwords', 'youtube', 'display', 'gmail', 'google_maps', 'google_play', 'google_discover', 'admob', 'waze']), 'google', if(notEmpty(source_name), source_name, 'organic'))))) AS source,
+ count() AS conversion_0
FROM
(
SELECT
person_id,
- conversion_timestamps[i] AS conversion_time,
- conversion_math_values[i] AS conversion_math_value,
- conversion_campaigns[i] AS conversion_campaign,
- conversion_sources[i] AS conversion_source,
- conversion_mediums[i] AS conversion_medium,
- conversion_contents[i] AS conversion_content,
- conversion_terms[i] AS conversion_term,
- conversion_referring_domains[i] AS conversion_referring_domain,
- conversion_gclids[i] AS conversion_gclid,
- conversion_fbclids[i] AS conversion_fbclid,
- conversion_gad_sources[i] AS conversion_gad_source,
- arrayMax(arrayFilter(x -> and(lessOrEquals(x, conversion_timestamps[i]), greaterOrEquals(x, minus(conversion_timestamps[i], 7776000))), utm_timestamps)) AS last_utm_timestamp,
- if(isNotNull(last_utm_timestamp), utm_campaigns[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_campaign,
- if(isNotNull(last_utm_timestamp), utm_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_source,
- if(isNotNull(last_utm_timestamp), utm_mediums[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_medium,
- if(isNotNull(last_utm_timestamp), utm_contents[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_content,
- if(isNotNull(last_utm_timestamp), utm_terms[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_term,
- if(isNotNull(last_utm_timestamp), utm_referring_domains[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_referring_domain,
- if(isNotNull(last_utm_timestamp), utm_gclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gclid,
- if(isNotNull(last_utm_timestamp), utm_fbclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_fbclid,
- if(isNotNull(last_utm_timestamp), utm_gad_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gad_source
+ if(notEmpty(conversion_campaign), conversion_campaign, if(notEmpty(fallback_campaign), fallback_campaign, '')) AS campaign_name,
+ if(notEmpty(conversion_source), conversion_source, if(notEmpty(fallback_source), fallback_source, '')) AS source_name,
+ if(notEmpty(conversion_medium), conversion_medium, if(notEmpty(fallback_medium), fallback_medium, '')) AS medium_name,
+ if(notEmpty(conversion_content), conversion_content, if(notEmpty(fallback_content), fallback_content, '')) AS content_name,
+ if(notEmpty(conversion_term), conversion_term, if(notEmpty(fallback_term), fallback_term, '')) AS term_name,
+ if(notEmpty(conversion_referring_domain), conversion_referring_domain, if(notEmpty(fallback_referring_domain), fallback_referring_domain, '')) AS referring_domain_name,
+ if(notEmpty(conversion_gclid), conversion_gclid, if(notEmpty(fallback_gclid), fallback_gclid, '')) AS gclid_name,
+ if(notEmpty(conversion_fbclid), conversion_fbclid, if(notEmpty(fallback_fbclid), fallback_fbclid, '')) AS fbclid_name,
+ if(notEmpty(conversion_gad_source), conversion_gad_source, if(notEmpty(fallback_gad_source), fallback_gad_source, '')) AS gad_source_name,
+ '-' AS campaign_id,
+ 1 AS conversion_value
FROM
(
SELECT
- events.person_id,
- arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,
- arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toFloat(1), 0))) AS conversion_math_values,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gad_source, '')), ''))) AS conversion_gad_sources,
- arrayFilter(x -> greater(x, 0), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toUnixTimestamp(events.timestamp), 0))) AS utm_timestamps,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS utm_campaigns,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_source, '')), ''))) AS utm_sources,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_medium, '')), ''))) AS utm_mediums,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_content, '')), ''))) AS utm_contents,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_term, '')), ''))) AS utm_terms,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS utm_referring_domains,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gclid, '')), ''))) AS utm_gclids,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$fbclid, '')), ''))) AS utm_fbclids,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gad_source, '')), ''))) AS utm_gad_sources
+ person_id,
+ conversion_timestamps[i] AS conversion_time,
+ conversion_math_values[i] AS conversion_math_value,
+ conversion_campaigns[i] AS conversion_campaign,
+ conversion_sources[i] AS conversion_source,
+ conversion_mediums[i] AS conversion_medium,
+ conversion_contents[i] AS conversion_content,
+ conversion_terms[i] AS conversion_term,
+ conversion_referring_domains[i] AS conversion_referring_domain,
+ conversion_gclids[i] AS conversion_gclid,
+ conversion_fbclids[i] AS conversion_fbclid,
+ conversion_gad_sources[i] AS conversion_gad_source,
+ arrayMax(arrayFilter(x -> and(lessOrEquals(x, conversion_timestamps[i]), greaterOrEquals(x, minus(conversion_timestamps[i], 7776000))), utm_timestamps)) AS last_utm_timestamp,
+ if(isNotNull(last_utm_timestamp), utm_campaigns[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_campaign,
+ if(isNotNull(last_utm_timestamp), utm_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_source,
+ if(isNotNull(last_utm_timestamp), utm_mediums[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_medium,
+ if(isNotNull(last_utm_timestamp), utm_contents[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_content,
+ if(isNotNull(last_utm_timestamp), utm_terms[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_term,
+ if(isNotNull(last_utm_timestamp), utm_referring_domains[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_referring_domain,
+ if(isNotNull(last_utm_timestamp), utm_gclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gclid,
+ if(isNotNull(last_utm_timestamp), utm_fbclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_fbclid,
+ if(isNotNull(last_utm_timestamp), utm_gad_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gad_source
FROM
- events
- WHERE
- or(and(equals(event, 'test_event'), greaterOrEquals(events.timestamp, toDateTime('2024-11-01 00:00:00')), lessOrEquals(events.timestamp, toDateTime('2024-12-31 23:59:59'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2024-11-01 00:00:00'), toIntervalSecond(7776000))), lessOrEquals(events.timestamp, toDateTime('2024-12-31 23:59:59'))))
- GROUP BY
- events.person_id
- HAVING
- greater(length(conversion_timestamps), 0))
- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
+ (
+ SELECT
+ events.person_id,
+ arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,
+ arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toFloat(1), 0))) AS conversion_math_values,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gad_source, '')), ''))) AS conversion_gad_sources,
+ arrayFilter(x -> greater(x, 0), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toUnixTimestamp(events.timestamp), 0))) AS utm_timestamps,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS utm_campaigns,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_source, '')), ''))) AS utm_sources,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_medium, '')), ''))) AS utm_mediums,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_content, '')), ''))) AS utm_contents,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_term, '')), ''))) AS utm_terms,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS utm_referring_domains,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gclid, '')), ''))) AS utm_gclids,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$fbclid, '')), ''))) AS utm_fbclids,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gad_source, '')), ''))) AS utm_gad_sources
+ FROM
+ events
+ WHERE
+ or(and(equals(event, 'test_event'), greaterOrEquals(events.timestamp, toDateTime('2024-11-01 00:00:00')), lessOrEquals(events.timestamp, toDateTime('2024-12-31 23:59:59'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2024-11-01 00:00:00'), toIntervalSecond(7776000))), lessOrEquals(events.timestamp, toDateTime('2024-12-31 23:59:59'))))
+ GROUP BY
+ events.person_id
+ HAVING
+ greater(length(conversion_timestamps), 0))
+ ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
+ GROUP BY
+ campaign,
+ id,
+ source) AS conv
GROUP BY
- campaign,
- id,
- source) AS conv
- GROUP BY
- conv.campaign,
- conv.id,
- conv.source)
- SELECT
- campaign_costs.id AS ID,
- campaign_costs.campaign AS Campaign,
- campaign_costs.source AS Source,
- round(campaign_costs.total_cost, 2) AS Cost,
- round(campaign_costs.total_clicks, 0) AS Clicks,
- round(campaign_costs.total_impressions, 0) AS Impressions,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
- round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
- round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
- round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
- round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`,
- ucg.conversion_0 AS `Sign Up Conversions`,
- round(divide(campaign_costs.total_cost, nullif(ucg.conversion_0, 0)), 2) AS `Cost per Sign Up Conversions`
- FROM
- campaign_costs
- LEFT JOIN ucg ON and(equals(campaign_costs.match_key, ucg.match_key), equals(campaign_costs.source, ucg.source))) AS current_period
- LEFT JOIN (WITH
- campaign_costs AS (
+ conv.campaign,
+ conv.id,
+ conv.source)
SELECT
- campaign,
- id,
- source,
- any(match_key) AS match_key,
- sum(ifNull(toFloat(cost), 0)) AS total_cost,
- sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
- sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
- sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
- sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
+ campaign_costs.id AS ID,
+ campaign_costs.campaign AS Campaign,
+ campaign_costs.source AS Source,
+ round(campaign_costs.total_cost, 2) AS Cost,
+ round(campaign_costs.total_clicks, 0) AS Clicks,
+ round(campaign_costs.total_impressions, 0) AS Impressions,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
+ round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
+ round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
+ round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
+ round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`,
+ ucg.conversion_0 AS `Sign Up Conversions`,
+ round(divide(campaign_costs.total_cost, nullif(ucg.conversion_0, 0)), 2) AS `Cost per Sign Up Conversions`
FROM
- (
+ campaign_costs
+ LEFT JOIN ucg ON and(equals(campaign_costs.match_key, ucg.match_key), equals(campaign_costs.source, ucg.source)))
+ UNION ALL
+ SELECT
+ 'previous' AS _period,
+ ID,
+ Campaign,
+ Source,
+ Cost,
+ Clicks,
+ Impressions,
+ CPC,
+ CTR,
+ `Reported Conversions`,
+ `Reported Conversion Value`,
+ `Reported ROAS`,
+ `Cost per Reported Conversions`,
+ `Sign Up Conversions`,
+ `Cost per Sign Up Conversions`
+ FROM
+ (WITH
+ campaign_costs AS (
SELECT
- toString(campaign1) AS match_key,
- toString(campaign1) AS campaign,
- toString(campaign1) AS id,
- toString('Facebook Ads') AS source,
- toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
- toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
- toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
- toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
- 0 AS reported_conversion_value
+ campaign,
+ id,
+ source,
+ any(match_key) AS match_key,
+ sum(ifNull(toFloat(cost), 0)) AS total_cost,
+ sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
+ sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
+ sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
+ sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
FROM
- `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
- WHERE
- and(greaterOrEquals(toDateTime(date1), toDateTime('2024-09-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-10-31 23:59:59'))))
- GROUP BY
- campaign,
- id,
- source),
- ucg AS (
- SELECT
- conv.campaign AS campaign,
- conv.id AS id,
- conv.source AS source,
- conv.campaign AS match_key,
- sum(conv.conversion_0) AS conversion_0
- FROM
- (
+ (
+ SELECT
+ toString(campaign1) AS match_key,
+ toString(campaign1) AS campaign,
+ toString(campaign1) AS id,
+ toString('Facebook Ads') AS source,
+ toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
+ toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
+ toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
+ toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
+ 0 AS reported_conversion_value
+ FROM
+ `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
+ WHERE
+ and(greaterOrEquals(toDateTime(date1), toDateTime('2024-09-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-10-31 23:59:59'))))
+ GROUP BY
+ campaign,
+ id,
+ source),
+ ucg AS (
SELECT
- if(notEmpty(campaign_name), campaign_name, 'organic') AS campaign,
- if(notEmpty(campaign_id), campaign_id, '-') AS id,
- if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['microsoft', 'msads', 'bing_video']), 'bing', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['facebook', 'instagram', 'messenger', 'fb', 'whatsapp', 'audience_network', 'facebook_marketplace', 'threads']), 'meta', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['li']), 'linkedin', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['adwords', 'youtube', 'display', 'gmail', 'google_maps', 'google_play', 'google_discover', 'admob', 'waze']), 'google', if(notEmpty(source_name), source_name, 'organic'))))) AS source,
- count() AS conversion_0
+ conv.campaign AS campaign,
+ conv.id AS id,
+ conv.source AS source,
+ conv.campaign AS match_key,
+ sum(conv.conversion_0) AS conversion_0
FROM
(
SELECT
- person_id,
- if(notEmpty(conversion_campaign), conversion_campaign, if(notEmpty(fallback_campaign), fallback_campaign, '')) AS campaign_name,
- if(notEmpty(conversion_source), conversion_source, if(notEmpty(fallback_source), fallback_source, '')) AS source_name,
- if(notEmpty(conversion_medium), conversion_medium, if(notEmpty(fallback_medium), fallback_medium, '')) AS medium_name,
- if(notEmpty(conversion_content), conversion_content, if(notEmpty(fallback_content), fallback_content, '')) AS content_name,
- if(notEmpty(conversion_term), conversion_term, if(notEmpty(fallback_term), fallback_term, '')) AS term_name,
- if(notEmpty(conversion_referring_domain), conversion_referring_domain, if(notEmpty(fallback_referring_domain), fallback_referring_domain, '')) AS referring_domain_name,
- if(notEmpty(conversion_gclid), conversion_gclid, if(notEmpty(fallback_gclid), fallback_gclid, '')) AS gclid_name,
- if(notEmpty(conversion_fbclid), conversion_fbclid, if(notEmpty(fallback_fbclid), fallback_fbclid, '')) AS fbclid_name,
- if(notEmpty(conversion_gad_source), conversion_gad_source, if(notEmpty(fallback_gad_source), fallback_gad_source, '')) AS gad_source_name,
- '-' AS campaign_id,
- 1 AS conversion_value
+ if(notEmpty(campaign_name), campaign_name, 'organic') AS campaign,
+ if(notEmpty(campaign_id), campaign_id, '-') AS id,
+ if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['microsoft', 'msads', 'bing_video']), 'bing', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['facebook', 'instagram', 'messenger', 'fb', 'whatsapp', 'audience_network', 'facebook_marketplace', 'threads']), 'meta', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['li']), 'linkedin', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['adwords', 'youtube', 'display', 'gmail', 'google_maps', 'google_play', 'google_discover', 'admob', 'waze']), 'google', if(notEmpty(source_name), source_name, 'organic'))))) AS source,
+ count() AS conversion_0
FROM
(
SELECT
person_id,
- conversion_timestamps[i] AS conversion_time,
- conversion_math_values[i] AS conversion_math_value,
- conversion_campaigns[i] AS conversion_campaign,
- conversion_sources[i] AS conversion_source,
- conversion_mediums[i] AS conversion_medium,
- conversion_contents[i] AS conversion_content,
- conversion_terms[i] AS conversion_term,
- conversion_referring_domains[i] AS conversion_referring_domain,
- conversion_gclids[i] AS conversion_gclid,
- conversion_fbclids[i] AS conversion_fbclid,
- conversion_gad_sources[i] AS conversion_gad_source,
- arrayMax(arrayFilter(x -> and(lessOrEquals(x, conversion_timestamps[i]), greaterOrEquals(x, minus(conversion_timestamps[i], 7776000))), utm_timestamps)) AS last_utm_timestamp,
- if(isNotNull(last_utm_timestamp), utm_campaigns[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_campaign,
- if(isNotNull(last_utm_timestamp), utm_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_source,
- if(isNotNull(last_utm_timestamp), utm_mediums[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_medium,
- if(isNotNull(last_utm_timestamp), utm_contents[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_content,
- if(isNotNull(last_utm_timestamp), utm_terms[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_term,
- if(isNotNull(last_utm_timestamp), utm_referring_domains[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_referring_domain,
- if(isNotNull(last_utm_timestamp), utm_gclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gclid,
- if(isNotNull(last_utm_timestamp), utm_fbclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_fbclid,
- if(isNotNull(last_utm_timestamp), utm_gad_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gad_source
+ if(notEmpty(conversion_campaign), conversion_campaign, if(notEmpty(fallback_campaign), fallback_campaign, '')) AS campaign_name,
+ if(notEmpty(conversion_source), conversion_source, if(notEmpty(fallback_source), fallback_source, '')) AS source_name,
+ if(notEmpty(conversion_medium), conversion_medium, if(notEmpty(fallback_medium), fallback_medium, '')) AS medium_name,
+ if(notEmpty(conversion_content), conversion_content, if(notEmpty(fallback_content), fallback_content, '')) AS content_name,
+ if(notEmpty(conversion_term), conversion_term, if(notEmpty(fallback_term), fallback_term, '')) AS term_name,
+ if(notEmpty(conversion_referring_domain), conversion_referring_domain, if(notEmpty(fallback_referring_domain), fallback_referring_domain, '')) AS referring_domain_name,
+ if(notEmpty(conversion_gclid), conversion_gclid, if(notEmpty(fallback_gclid), fallback_gclid, '')) AS gclid_name,
+ if(notEmpty(conversion_fbclid), conversion_fbclid, if(notEmpty(fallback_fbclid), fallback_fbclid, '')) AS fbclid_name,
+ if(notEmpty(conversion_gad_source), conversion_gad_source, if(notEmpty(fallback_gad_source), fallback_gad_source, '')) AS gad_source_name,
+ '-' AS campaign_id,
+ 1 AS conversion_value
FROM
(
SELECT
- events.person_id,
- arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,
- arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toFloat(1), 0))) AS conversion_math_values,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gad_source, '')), ''))) AS conversion_gad_sources,
- arrayFilter(x -> greater(x, 0), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toUnixTimestamp(events.timestamp), 0))) AS utm_timestamps,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS utm_campaigns,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_source, '')), ''))) AS utm_sources,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_medium, '')), ''))) AS utm_mediums,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_content, '')), ''))) AS utm_contents,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_term, '')), ''))) AS utm_terms,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS utm_referring_domains,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gclid, '')), ''))) AS utm_gclids,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$fbclid, '')), ''))) AS utm_fbclids,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gad_source, '')), ''))) AS utm_gad_sources
+ person_id,
+ conversion_timestamps[i] AS conversion_time,
+ conversion_math_values[i] AS conversion_math_value,
+ conversion_campaigns[i] AS conversion_campaign,
+ conversion_sources[i] AS conversion_source,
+ conversion_mediums[i] AS conversion_medium,
+ conversion_contents[i] AS conversion_content,
+ conversion_terms[i] AS conversion_term,
+ conversion_referring_domains[i] AS conversion_referring_domain,
+ conversion_gclids[i] AS conversion_gclid,
+ conversion_fbclids[i] AS conversion_fbclid,
+ conversion_gad_sources[i] AS conversion_gad_source,
+ arrayMax(arrayFilter(x -> and(lessOrEquals(x, conversion_timestamps[i]), greaterOrEquals(x, minus(conversion_timestamps[i], 7776000))), utm_timestamps)) AS last_utm_timestamp,
+ if(isNotNull(last_utm_timestamp), utm_campaigns[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_campaign,
+ if(isNotNull(last_utm_timestamp), utm_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_source,
+ if(isNotNull(last_utm_timestamp), utm_mediums[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_medium,
+ if(isNotNull(last_utm_timestamp), utm_contents[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_content,
+ if(isNotNull(last_utm_timestamp), utm_terms[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_term,
+ if(isNotNull(last_utm_timestamp), utm_referring_domains[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_referring_domain,
+ if(isNotNull(last_utm_timestamp), utm_gclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gclid,
+ if(isNotNull(last_utm_timestamp), utm_fbclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_fbclid,
+ if(isNotNull(last_utm_timestamp), utm_gad_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gad_source
FROM
- events
- WHERE
- or(and(equals(event, 'test_event'), greaterOrEquals(events.timestamp, toDateTime('2024-09-01 00:00:00')), lessOrEquals(events.timestamp, toDateTime('2024-10-31 23:59:59'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2024-09-01 00:00:00'), toIntervalSecond(7776000))), lessOrEquals(events.timestamp, toDateTime('2024-10-31 23:59:59'))))
- GROUP BY
- events.person_id
- HAVING
- greater(length(conversion_timestamps), 0))
- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
+ (
+ SELECT
+ events.person_id,
+ arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,
+ arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toFloat(1), 0))) AS conversion_math_values,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gad_source, '')), ''))) AS conversion_gad_sources,
+ arrayFilter(x -> greater(x, 0), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toUnixTimestamp(events.timestamp), 0))) AS utm_timestamps,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS utm_campaigns,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_source, '')), ''))) AS utm_sources,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_medium, '')), ''))) AS utm_mediums,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_content, '')), ''))) AS utm_contents,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_term, '')), ''))) AS utm_terms,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS utm_referring_domains,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gclid, '')), ''))) AS utm_gclids,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$fbclid, '')), ''))) AS utm_fbclids,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gad_source, '')), ''))) AS utm_gad_sources
+ FROM
+ events
+ WHERE
+ or(and(equals(event, 'test_event'), greaterOrEquals(events.timestamp, toDateTime('2024-09-01 00:00:00')), lessOrEquals(events.timestamp, toDateTime('2024-10-31 23:59:59'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2024-09-01 00:00:00'), toIntervalSecond(7776000))), lessOrEquals(events.timestamp, toDateTime('2024-10-31 23:59:59'))))
+ GROUP BY
+ events.person_id
+ HAVING
+ greater(length(conversion_timestamps), 0))
+ ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
+ GROUP BY
+ campaign,
+ id,
+ source) AS conv
GROUP BY
- campaign,
- id,
- source) AS conv
- GROUP BY
- conv.campaign,
- conv.id,
- conv.source)
- SELECT
- campaign_costs.id AS ID,
- campaign_costs.campaign AS Campaign,
- campaign_costs.source AS Source,
- round(campaign_costs.total_cost, 2) AS Cost,
- round(campaign_costs.total_clicks, 0) AS Clicks,
- round(campaign_costs.total_impressions, 0) AS Impressions,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
- round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
- round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
- round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
- round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`,
- ucg.conversion_0 AS `Sign Up Conversions`,
- round(divide(campaign_costs.total_cost, nullif(ucg.conversion_0, 0)), 2) AS `Cost per Sign Up Conversions`
- FROM
- campaign_costs
- LEFT JOIN ucg ON and(equals(campaign_costs.match_key, ucg.match_key), equals(campaign_costs.source, ucg.source))) AS previous_period ON and(equals(current_period.Campaign, previous_period.Campaign), equals(current_period.Source, previous_period.Source))
+ conv.campaign,
+ conv.id,
+ conv.source)
+ SELECT
+ campaign_costs.id AS ID,
+ campaign_costs.campaign AS Campaign,
+ campaign_costs.source AS Source,
+ round(campaign_costs.total_cost, 2) AS Cost,
+ round(campaign_costs.total_clicks, 0) AS Clicks,
+ round(campaign_costs.total_impressions, 0) AS Impressions,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
+ round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
+ round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
+ round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
+ round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`,
+ ucg.conversion_0 AS `Sign Up Conversions`,
+ round(divide(campaign_costs.total_cost, nullif(ucg.conversion_0, 0)), 2) AS `Cost per Sign Up Conversions`
+ FROM
+ campaign_costs
+ LEFT JOIN ucg ON and(equals(campaign_costs.match_key, ucg.match_key), equals(campaign_costs.source, ucg.source)))) AS combined
+ GROUP BY
+ combined.Campaign,
+ combined.Source
+ HAVING
+ greater(countIf(equals(combined._period, 'current')), 0)
ORDER BY
Cost DESC,
ID ASC
@@ -376,313 +417,354 @@
'''
SELECT
- tuple(current_period.ID, previous_period.ID) AS ID,
- tuple(current_period.Campaign, previous_period.Campaign) AS Campaign,
- tuple(current_period.Source, previous_period.Source) AS Source,
- tuple(current_period.Cost, previous_period.Cost) AS Cost,
- tuple(current_period.Clicks, previous_period.Clicks) AS Clicks,
- tuple(current_period.Impressions, previous_period.Impressions) AS Impressions,
- tuple(current_period.CPC, previous_period.CPC) AS CPC,
- tuple(current_period.CTR, previous_period.CTR) AS CTR,
- tuple(current_period.`Reported Conversions`, previous_period.`Reported Conversions`) AS `Reported Conversions`,
- tuple(current_period.`Reported Conversion Value`, previous_period.`Reported Conversion Value`) AS `Reported Conversion Value`,
- tuple(current_period.`Reported ROAS`, previous_period.`Reported ROAS`) AS `Reported ROAS`,
- tuple(current_period.`Cost per Reported Conversions`, previous_period.`Cost per Reported Conversions`) AS `Cost per Reported Conversions`,
- tuple(current_period.`Sign Up Conversions`, previous_period.`Sign Up Conversions`) AS `Sign Up Conversions`,
- tuple(current_period.`Cost per Sign Up Conversions`, previous_period.`Cost per Sign Up Conversions`) AS `Cost per Sign Up Conversions`
+ tuple(anyIf(combined.ID, equals(combined._period, 'current')), anyIf(combined.ID, equals(combined._period, 'previous'))) AS ID,
+ tuple(anyIf(combined.Campaign, equals(combined._period, 'current')), anyIf(combined.Campaign, equals(combined._period, 'previous'))) AS Campaign,
+ tuple(anyIf(combined.Source, equals(combined._period, 'current')), anyIf(combined.Source, equals(combined._period, 'previous'))) AS Source,
+ tuple(anyIf(combined.Cost, equals(combined._period, 'current')), anyIf(combined.Cost, equals(combined._period, 'previous'))) AS Cost,
+ tuple(anyIf(combined.Clicks, equals(combined._period, 'current')), anyIf(combined.Clicks, equals(combined._period, 'previous'))) AS Clicks,
+ tuple(anyIf(combined.Impressions, equals(combined._period, 'current')), anyIf(combined.Impressions, equals(combined._period, 'previous'))) AS Impressions,
+ tuple(anyIf(combined.CPC, equals(combined._period, 'current')), anyIf(combined.CPC, equals(combined._period, 'previous'))) AS CPC,
+ tuple(anyIf(combined.CTR, equals(combined._period, 'current')), anyIf(combined.CTR, equals(combined._period, 'previous'))) AS CTR,
+ tuple(anyIf(combined.`Reported Conversions`, equals(combined._period, 'current')), anyIf(combined.`Reported Conversions`, equals(combined._period, 'previous'))) AS `Reported Conversions`,
+ tuple(anyIf(combined.`Reported Conversion Value`, equals(combined._period, 'current')), anyIf(combined.`Reported Conversion Value`, equals(combined._period, 'previous'))) AS `Reported Conversion Value`,
+ tuple(anyIf(combined.`Reported ROAS`, equals(combined._period, 'current')), anyIf(combined.`Reported ROAS`, equals(combined._period, 'previous'))) AS `Reported ROAS`,
+ tuple(anyIf(combined.`Cost per Reported Conversions`, equals(combined._period, 'current')), anyIf(combined.`Cost per Reported Conversions`, equals(combined._period, 'previous'))) AS `Cost per Reported Conversions`,
+ tuple(anyIf(combined.`Sign Up Conversions`, equals(combined._period, 'current')), anyIf(combined.`Sign Up Conversions`, equals(combined._period, 'previous'))) AS `Sign Up Conversions`,
+ tuple(anyIf(combined.`Cost per Sign Up Conversions`, equals(combined._period, 'current')), anyIf(combined.`Cost per Sign Up Conversions`, equals(combined._period, 'previous'))) AS `Cost per Sign Up Conversions`
FROM
- (WITH
- campaign_costs AS (
- SELECT
- campaign,
- id,
- source,
- any(match_key) AS match_key,
- sum(ifNull(toFloat(cost), 0)) AS total_cost,
- sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
- sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
- sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
- sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
- FROM
- (
+ (
+ SELECT
+ 'current' AS _period,
+ ID,
+ Campaign,
+ Source,
+ Cost,
+ Clicks,
+ Impressions,
+ CPC,
+ CTR,
+ `Reported Conversions`,
+ `Reported Conversion Value`,
+ `Reported ROAS`,
+ `Cost per Reported Conversions`,
+ `Sign Up Conversions`,
+ `Cost per Sign Up Conversions`
+ FROM
+ (WITH
+ campaign_costs AS (
SELECT
- toString(campaign1) AS match_key,
- toString(campaign1) AS campaign,
- toString(campaign1) AS id,
- toString('Facebook Ads') AS source,
- toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
- toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
- toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
- toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
- 0 AS reported_conversion_value
+ campaign,
+ id,
+ source,
+ any(match_key) AS match_key,
+ sum(ifNull(toFloat(cost), 0)) AS total_cost,
+ sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
+ sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
+ sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
+ sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
FROM
- `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
- WHERE
- and(greaterOrEquals(toDateTime(date1), toDateTime('2024-11-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-12-31 23:59:59'))))
- GROUP BY
- campaign,
- id,
- source),
- ucg AS (
- SELECT
- conv.campaign AS campaign,
- conv.id AS id,
- conv.source AS source,
- conv.campaign AS match_key,
- sum(conv.conversion_0) AS conversion_0
- FROM
- (
+ (
+ SELECT
+ toString(campaign1) AS match_key,
+ toString(campaign1) AS campaign,
+ toString(campaign1) AS id,
+ toString('Facebook Ads') AS source,
+ toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
+ toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
+ toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
+ toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
+ 0 AS reported_conversion_value
+ FROM
+ `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
+ WHERE
+ and(greaterOrEquals(toDateTime(date1), toDateTime('2024-11-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-12-31 23:59:59'))))
+ GROUP BY
+ campaign,
+ id,
+ source),
+ ucg AS (
SELECT
- if(notEmpty(campaign_name), campaign_name, 'organic') AS campaign,
- if(notEmpty(campaign_id), campaign_id, '-') AS id,
- if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['microsoft', 'msads', 'bing_video']), 'bing', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['facebook', 'instagram', 'messenger', 'fb', 'whatsapp', 'audience_network', 'facebook_marketplace', 'threads']), 'meta', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['li']), 'linkedin', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['adwords', 'youtube', 'display', 'gmail', 'google_maps', 'google_play', 'google_discover', 'admob', 'waze']), 'google', if(notEmpty(source_name), source_name, 'organic'))))) AS source,
- count() AS conversion_0
+ conv.campaign AS campaign,
+ conv.id AS id,
+ conv.source AS source,
+ conv.campaign AS match_key,
+ sum(conv.conversion_0) AS conversion_0
FROM
(
SELECT
- person_id,
- if(notEmpty(conversion_campaign), conversion_campaign, if(notEmpty(fallback_campaign), fallback_campaign, '')) AS campaign_name,
- if(notEmpty(conversion_source), conversion_source, if(notEmpty(fallback_source), fallback_source, '')) AS source_name,
- if(notEmpty(conversion_medium), conversion_medium, if(notEmpty(fallback_medium), fallback_medium, '')) AS medium_name,
- if(notEmpty(conversion_content), conversion_content, if(notEmpty(fallback_content), fallback_content, '')) AS content_name,
- if(notEmpty(conversion_term), conversion_term, if(notEmpty(fallback_term), fallback_term, '')) AS term_name,
- if(notEmpty(conversion_referring_domain), conversion_referring_domain, if(notEmpty(fallback_referring_domain), fallback_referring_domain, '')) AS referring_domain_name,
- if(notEmpty(conversion_gclid), conversion_gclid, if(notEmpty(fallback_gclid), fallback_gclid, '')) AS gclid_name,
- if(notEmpty(conversion_fbclid), conversion_fbclid, if(notEmpty(fallback_fbclid), fallback_fbclid, '')) AS fbclid_name,
- if(notEmpty(conversion_gad_source), conversion_gad_source, if(notEmpty(fallback_gad_source), fallback_gad_source, '')) AS gad_source_name,
- '-' AS campaign_id,
- 1 AS conversion_value
+ if(notEmpty(campaign_name), campaign_name, 'organic') AS campaign,
+ if(notEmpty(campaign_id), campaign_id, '-') AS id,
+ if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['microsoft', 'msads', 'bing_video']), 'bing', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['facebook', 'instagram', 'messenger', 'fb', 'whatsapp', 'audience_network', 'facebook_marketplace', 'threads']), 'meta', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['li']), 'linkedin', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['adwords', 'youtube', 'display', 'gmail', 'google_maps', 'google_play', 'google_discover', 'admob', 'waze']), 'google', if(notEmpty(source_name), source_name, 'organic'))))) AS source,
+ count() AS conversion_0
FROM
(
SELECT
person_id,
- conversion_timestamps[i] AS conversion_time,
- conversion_math_values[i] AS conversion_math_value,
- conversion_campaigns[i] AS conversion_campaign,
- conversion_sources[i] AS conversion_source,
- conversion_mediums[i] AS conversion_medium,
- conversion_contents[i] AS conversion_content,
- conversion_terms[i] AS conversion_term,
- conversion_referring_domains[i] AS conversion_referring_domain,
- conversion_gclids[i] AS conversion_gclid,
- conversion_fbclids[i] AS conversion_fbclid,
- conversion_gad_sources[i] AS conversion_gad_source,
- arrayMax(arrayFilter(x -> and(lessOrEquals(x, conversion_timestamps[i]), greaterOrEquals(x, minus(conversion_timestamps[i], 7776000))), utm_timestamps)) AS last_utm_timestamp,
- if(isNotNull(last_utm_timestamp), utm_campaigns[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_campaign,
- if(isNotNull(last_utm_timestamp), utm_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_source,
- if(isNotNull(last_utm_timestamp), utm_mediums[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_medium,
- if(isNotNull(last_utm_timestamp), utm_contents[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_content,
- if(isNotNull(last_utm_timestamp), utm_terms[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_term,
- if(isNotNull(last_utm_timestamp), utm_referring_domains[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_referring_domain,
- if(isNotNull(last_utm_timestamp), utm_gclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gclid,
- if(isNotNull(last_utm_timestamp), utm_fbclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_fbclid,
- if(isNotNull(last_utm_timestamp), utm_gad_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gad_source
+ if(notEmpty(conversion_campaign), conversion_campaign, if(notEmpty(fallback_campaign), fallback_campaign, '')) AS campaign_name,
+ if(notEmpty(conversion_source), conversion_source, if(notEmpty(fallback_source), fallback_source, '')) AS source_name,
+ if(notEmpty(conversion_medium), conversion_medium, if(notEmpty(fallback_medium), fallback_medium, '')) AS medium_name,
+ if(notEmpty(conversion_content), conversion_content, if(notEmpty(fallback_content), fallback_content, '')) AS content_name,
+ if(notEmpty(conversion_term), conversion_term, if(notEmpty(fallback_term), fallback_term, '')) AS term_name,
+ if(notEmpty(conversion_referring_domain), conversion_referring_domain, if(notEmpty(fallback_referring_domain), fallback_referring_domain, '')) AS referring_domain_name,
+ if(notEmpty(conversion_gclid), conversion_gclid, if(notEmpty(fallback_gclid), fallback_gclid, '')) AS gclid_name,
+ if(notEmpty(conversion_fbclid), conversion_fbclid, if(notEmpty(fallback_fbclid), fallback_fbclid, '')) AS fbclid_name,
+ if(notEmpty(conversion_gad_source), conversion_gad_source, if(notEmpty(fallback_gad_source), fallback_gad_source, '')) AS gad_source_name,
+ '-' AS campaign_id,
+ 1 AS conversion_value
FROM
(
SELECT
- events.person_id,
- arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,
- arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toFloat(1), 0))) AS conversion_math_values,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gad_source, '')), ''))) AS conversion_gad_sources,
- arrayFilter(x -> greater(x, 0), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toUnixTimestamp(events.timestamp), 0))) AS utm_timestamps,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS utm_campaigns,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_source, '')), ''))) AS utm_sources,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_medium, '')), ''))) AS utm_mediums,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_content, '')), ''))) AS utm_contents,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_term, '')), ''))) AS utm_terms,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS utm_referring_domains,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gclid, '')), ''))) AS utm_gclids,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$fbclid, '')), ''))) AS utm_fbclids,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gad_source, '')), ''))) AS utm_gad_sources
+ person_id,
+ conversion_timestamps[i] AS conversion_time,
+ conversion_math_values[i] AS conversion_math_value,
+ conversion_campaigns[i] AS conversion_campaign,
+ conversion_sources[i] AS conversion_source,
+ conversion_mediums[i] AS conversion_medium,
+ conversion_contents[i] AS conversion_content,
+ conversion_terms[i] AS conversion_term,
+ conversion_referring_domains[i] AS conversion_referring_domain,
+ conversion_gclids[i] AS conversion_gclid,
+ conversion_fbclids[i] AS conversion_fbclid,
+ conversion_gad_sources[i] AS conversion_gad_source,
+ arrayMax(arrayFilter(x -> and(lessOrEquals(x, conversion_timestamps[i]), greaterOrEquals(x, minus(conversion_timestamps[i], 7776000))), utm_timestamps)) AS last_utm_timestamp,
+ if(isNotNull(last_utm_timestamp), utm_campaigns[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_campaign,
+ if(isNotNull(last_utm_timestamp), utm_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_source,
+ if(isNotNull(last_utm_timestamp), utm_mediums[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_medium,
+ if(isNotNull(last_utm_timestamp), utm_contents[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_content,
+ if(isNotNull(last_utm_timestamp), utm_terms[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_term,
+ if(isNotNull(last_utm_timestamp), utm_referring_domains[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_referring_domain,
+ if(isNotNull(last_utm_timestamp), utm_gclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gclid,
+ if(isNotNull(last_utm_timestamp), utm_fbclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_fbclid,
+ if(isNotNull(last_utm_timestamp), utm_gad_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gad_source
FROM
- events
- WHERE
- or(and(equals(event, 'test_event'), greaterOrEquals(events.timestamp, toDateTime('2024-11-01 00:00:00')), lessOrEquals(events.timestamp, toDateTime('2024-12-31 23:59:59'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2024-11-01 00:00:00'), toIntervalSecond(7776000))), lessOrEquals(events.timestamp, toDateTime('2024-12-31 23:59:59'))))
- GROUP BY
- events.person_id
- HAVING
- greater(length(conversion_timestamps), 0))
- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
+ (
+ SELECT
+ events.person_id,
+ arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,
+ arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toFloat(1), 0))) AS conversion_math_values,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gad_source, '')), ''))) AS conversion_gad_sources,
+ arrayFilter(x -> greater(x, 0), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toUnixTimestamp(events.timestamp), 0))) AS utm_timestamps,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS utm_campaigns,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_source, '')), ''))) AS utm_sources,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_medium, '')), ''))) AS utm_mediums,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_content, '')), ''))) AS utm_contents,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_term, '')), ''))) AS utm_terms,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS utm_referring_domains,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gclid, '')), ''))) AS utm_gclids,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$fbclid, '')), ''))) AS utm_fbclids,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gad_source, '')), ''))) AS utm_gad_sources
+ FROM
+ events
+ WHERE
+ or(and(equals(event, 'test_event'), greaterOrEquals(events.timestamp, toDateTime('2024-11-01 00:00:00')), lessOrEquals(events.timestamp, toDateTime('2024-12-31 23:59:59'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2024-11-01 00:00:00'), toIntervalSecond(7776000))), lessOrEquals(events.timestamp, toDateTime('2024-12-31 23:59:59'))))
+ GROUP BY
+ events.person_id
+ HAVING
+ greater(length(conversion_timestamps), 0))
+ ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
+ GROUP BY
+ campaign,
+ id,
+ source) AS conv
GROUP BY
- campaign,
- id,
- source) AS conv
- GROUP BY
- conv.campaign,
- conv.id,
- conv.source)
- SELECT
- campaign_costs.id AS ID,
- campaign_costs.campaign AS Campaign,
- campaign_costs.source AS Source,
- round(campaign_costs.total_cost, 2) AS Cost,
- round(campaign_costs.total_clicks, 0) AS Clicks,
- round(campaign_costs.total_impressions, 0) AS Impressions,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
- round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
- round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
- round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
- round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`,
- ucg.conversion_0 AS `Sign Up Conversions`,
- round(divide(campaign_costs.total_cost, nullif(ucg.conversion_0, 0)), 2) AS `Cost per Sign Up Conversions`
- FROM
- campaign_costs
- LEFT JOIN ucg ON and(equals(campaign_costs.match_key, ucg.match_key), equals(campaign_costs.source, ucg.source))) AS current_period
- LEFT JOIN (WITH
- campaign_costs AS (
+ conv.campaign,
+ conv.id,
+ conv.source)
SELECT
- campaign,
- id,
- source,
- any(match_key) AS match_key,
- sum(ifNull(toFloat(cost), 0)) AS total_cost,
- sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
- sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
- sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
- sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
+ campaign_costs.id AS ID,
+ campaign_costs.campaign AS Campaign,
+ campaign_costs.source AS Source,
+ round(campaign_costs.total_cost, 2) AS Cost,
+ round(campaign_costs.total_clicks, 0) AS Clicks,
+ round(campaign_costs.total_impressions, 0) AS Impressions,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
+ round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
+ round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
+ round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
+ round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`,
+ ucg.conversion_0 AS `Sign Up Conversions`,
+ round(divide(campaign_costs.total_cost, nullif(ucg.conversion_0, 0)), 2) AS `Cost per Sign Up Conversions`
FROM
- (
+ campaign_costs
+ LEFT JOIN ucg ON and(equals(campaign_costs.match_key, ucg.match_key), equals(campaign_costs.source, ucg.source)))
+ UNION ALL
+ SELECT
+ 'previous' AS _period,
+ ID,
+ Campaign,
+ Source,
+ Cost,
+ Clicks,
+ Impressions,
+ CPC,
+ CTR,
+ `Reported Conversions`,
+ `Reported Conversion Value`,
+ `Reported ROAS`,
+ `Cost per Reported Conversions`,
+ `Sign Up Conversions`,
+ `Cost per Sign Up Conversions`
+ FROM
+ (WITH
+ campaign_costs AS (
SELECT
- toString(campaign1) AS match_key,
- toString(campaign1) AS campaign,
- toString(campaign1) AS id,
- toString('Facebook Ads') AS source,
- toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
- toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
- toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
- toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
- 0 AS reported_conversion_value
+ campaign,
+ id,
+ source,
+ any(match_key) AS match_key,
+ sum(ifNull(toFloat(cost), 0)) AS total_cost,
+ sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
+ sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
+ sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
+ sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
FROM
- `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
- WHERE
- and(greaterOrEquals(toDateTime(date1), toDateTime('2024-09-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-10-31 23:59:59'))))
- GROUP BY
- campaign,
- id,
- source),
- ucg AS (
- SELECT
- conv.campaign AS campaign,
- conv.id AS id,
- conv.source AS source,
- conv.campaign AS match_key,
- sum(conv.conversion_0) AS conversion_0
- FROM
- (
+ (
+ SELECT
+ toString(campaign1) AS match_key,
+ toString(campaign1) AS campaign,
+ toString(campaign1) AS id,
+ toString('Facebook Ads') AS source,
+ toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
+ toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
+ toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
+ toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
+ 0 AS reported_conversion_value
+ FROM
+ `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
+ WHERE
+ and(greaterOrEquals(toDateTime(date1), toDateTime('2024-09-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-10-31 23:59:59'))))
+ GROUP BY
+ campaign,
+ id,
+ source),
+ ucg AS (
SELECT
- if(notEmpty(campaign_name), campaign_name, 'organic') AS campaign,
- if(notEmpty(campaign_id), campaign_id, '-') AS id,
- if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['microsoft', 'msads', 'bing_video']), 'bing', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['facebook', 'instagram', 'messenger', 'fb', 'whatsapp', 'audience_network', 'facebook_marketplace', 'threads']), 'meta', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['li']), 'linkedin', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['adwords', 'youtube', 'display', 'gmail', 'google_maps', 'google_play', 'google_discover', 'admob', 'waze']), 'google', if(notEmpty(source_name), source_name, 'organic'))))) AS source,
- count() AS conversion_0
+ conv.campaign AS campaign,
+ conv.id AS id,
+ conv.source AS source,
+ conv.campaign AS match_key,
+ sum(conv.conversion_0) AS conversion_0
FROM
(
SELECT
- person_id,
- if(notEmpty(conversion_campaign), conversion_campaign, if(notEmpty(fallback_campaign), fallback_campaign, '')) AS campaign_name,
- if(notEmpty(conversion_source), conversion_source, if(notEmpty(fallback_source), fallback_source, '')) AS source_name,
- if(notEmpty(conversion_medium), conversion_medium, if(notEmpty(fallback_medium), fallback_medium, '')) AS medium_name,
- if(notEmpty(conversion_content), conversion_content, if(notEmpty(fallback_content), fallback_content, '')) AS content_name,
- if(notEmpty(conversion_term), conversion_term, if(notEmpty(fallback_term), fallback_term, '')) AS term_name,
- if(notEmpty(conversion_referring_domain), conversion_referring_domain, if(notEmpty(fallback_referring_domain), fallback_referring_domain, '')) AS referring_domain_name,
- if(notEmpty(conversion_gclid), conversion_gclid, if(notEmpty(fallback_gclid), fallback_gclid, '')) AS gclid_name,
- if(notEmpty(conversion_fbclid), conversion_fbclid, if(notEmpty(fallback_fbclid), fallback_fbclid, '')) AS fbclid_name,
- if(notEmpty(conversion_gad_source), conversion_gad_source, if(notEmpty(fallback_gad_source), fallback_gad_source, '')) AS gad_source_name,
- '-' AS campaign_id,
- 1 AS conversion_value
+ if(notEmpty(campaign_name), campaign_name, 'organic') AS campaign,
+ if(notEmpty(campaign_id), campaign_id, '-') AS id,
+ if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['microsoft', 'msads', 'bing_video']), 'bing', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['facebook', 'instagram', 'messenger', 'fb', 'whatsapp', 'audience_network', 'facebook_marketplace', 'threads']), 'meta', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['li']), 'linkedin', if(in(lower(if(notEmpty(source_name), source_name, 'organic')), ['adwords', 'youtube', 'display', 'gmail', 'google_maps', 'google_play', 'google_discover', 'admob', 'waze']), 'google', if(notEmpty(source_name), source_name, 'organic'))))) AS source,
+ count() AS conversion_0
FROM
(
SELECT
person_id,
- conversion_timestamps[i] AS conversion_time,
- conversion_math_values[i] AS conversion_math_value,
- conversion_campaigns[i] AS conversion_campaign,
- conversion_sources[i] AS conversion_source,
- conversion_mediums[i] AS conversion_medium,
- conversion_contents[i] AS conversion_content,
- conversion_terms[i] AS conversion_term,
- conversion_referring_domains[i] AS conversion_referring_domain,
- conversion_gclids[i] AS conversion_gclid,
- conversion_fbclids[i] AS conversion_fbclid,
- conversion_gad_sources[i] AS conversion_gad_source,
- arrayMax(arrayFilter(x -> and(lessOrEquals(x, conversion_timestamps[i]), greaterOrEquals(x, minus(conversion_timestamps[i], 7776000))), utm_timestamps)) AS last_utm_timestamp,
- if(isNotNull(last_utm_timestamp), utm_campaigns[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_campaign,
- if(isNotNull(last_utm_timestamp), utm_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_source,
- if(isNotNull(last_utm_timestamp), utm_mediums[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_medium,
- if(isNotNull(last_utm_timestamp), utm_contents[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_content,
- if(isNotNull(last_utm_timestamp), utm_terms[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_term,
- if(isNotNull(last_utm_timestamp), utm_referring_domains[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_referring_domain,
- if(isNotNull(last_utm_timestamp), utm_gclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gclid,
- if(isNotNull(last_utm_timestamp), utm_fbclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_fbclid,
- if(isNotNull(last_utm_timestamp), utm_gad_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gad_source
+ if(notEmpty(conversion_campaign), conversion_campaign, if(notEmpty(fallback_campaign), fallback_campaign, '')) AS campaign_name,
+ if(notEmpty(conversion_source), conversion_source, if(notEmpty(fallback_source), fallback_source, '')) AS source_name,
+ if(notEmpty(conversion_medium), conversion_medium, if(notEmpty(fallback_medium), fallback_medium, '')) AS medium_name,
+ if(notEmpty(conversion_content), conversion_content, if(notEmpty(fallback_content), fallback_content, '')) AS content_name,
+ if(notEmpty(conversion_term), conversion_term, if(notEmpty(fallback_term), fallback_term, '')) AS term_name,
+ if(notEmpty(conversion_referring_domain), conversion_referring_domain, if(notEmpty(fallback_referring_domain), fallback_referring_domain, '')) AS referring_domain_name,
+ if(notEmpty(conversion_gclid), conversion_gclid, if(notEmpty(fallback_gclid), fallback_gclid, '')) AS gclid_name,
+ if(notEmpty(conversion_fbclid), conversion_fbclid, if(notEmpty(fallback_fbclid), fallback_fbclid, '')) AS fbclid_name,
+ if(notEmpty(conversion_gad_source), conversion_gad_source, if(notEmpty(fallback_gad_source), fallback_gad_source, '')) AS gad_source_name,
+ '-' AS campaign_id,
+ 1 AS conversion_value
FROM
(
SELECT
- events.person_id,
- arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,
- arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toFloat(1), 0))) AS conversion_math_values,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,
- arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gad_source, '')), ''))) AS conversion_gad_sources,
- arrayFilter(x -> greater(x, 0), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toUnixTimestamp(events.timestamp), 0))) AS utm_timestamps,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS utm_campaigns,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_source, '')), ''))) AS utm_sources,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_medium, '')), ''))) AS utm_mediums,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_content, '')), ''))) AS utm_contents,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_term, '')), ''))) AS utm_terms,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS utm_referring_domains,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gclid, '')), ''))) AS utm_gclids,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$fbclid, '')), ''))) AS utm_fbclids,
- arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gad_source, '')), ''))) AS utm_gad_sources
+ person_id,
+ conversion_timestamps[i] AS conversion_time,
+ conversion_math_values[i] AS conversion_math_value,
+ conversion_campaigns[i] AS conversion_campaign,
+ conversion_sources[i] AS conversion_source,
+ conversion_mediums[i] AS conversion_medium,
+ conversion_contents[i] AS conversion_content,
+ conversion_terms[i] AS conversion_term,
+ conversion_referring_domains[i] AS conversion_referring_domain,
+ conversion_gclids[i] AS conversion_gclid,
+ conversion_fbclids[i] AS conversion_fbclid,
+ conversion_gad_sources[i] AS conversion_gad_source,
+ arrayMax(arrayFilter(x -> and(lessOrEquals(x, conversion_timestamps[i]), greaterOrEquals(x, minus(conversion_timestamps[i], 7776000))), utm_timestamps)) AS last_utm_timestamp,
+ if(isNotNull(last_utm_timestamp), utm_campaigns[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_campaign,
+ if(isNotNull(last_utm_timestamp), utm_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_source,
+ if(isNotNull(last_utm_timestamp), utm_mediums[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_medium,
+ if(isNotNull(last_utm_timestamp), utm_contents[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_content,
+ if(isNotNull(last_utm_timestamp), utm_terms[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_term,
+ if(isNotNull(last_utm_timestamp), utm_referring_domains[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_referring_domain,
+ if(isNotNull(last_utm_timestamp), utm_gclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gclid,
+ if(isNotNull(last_utm_timestamp), utm_fbclids[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_fbclid,
+ if(isNotNull(last_utm_timestamp), utm_gad_sources[indexOf(utm_timestamps, last_utm_timestamp)], '') AS fallback_gad_source
FROM
- events
- WHERE
- or(and(equals(event, 'test_event'), greaterOrEquals(events.timestamp, toDateTime('2024-09-01 00:00:00')), lessOrEquals(events.timestamp, toDateTime('2024-10-31 23:59:59'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2024-09-01 00:00:00'), toIntervalSecond(7776000))), lessOrEquals(events.timestamp, toDateTime('2024-10-31 23:59:59'))))
- GROUP BY
- events.person_id
- HAVING
- greater(length(conversion_timestamps), 0))
- ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
+ (
+ SELECT
+ events.person_id,
+ arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toUnixTimestamp(events.timestamp), 0))) AS conversion_timestamps,
+ arrayFilter(x -> greater(x, 0), groupArray(if(equals(event, 'test_event'), toFloat(1), 0))) AS conversion_math_values,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS conversion_campaigns,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_source, '')), ''))) AS conversion_sources,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_medium, '')), ''))) AS conversion_mediums,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_content, '')), ''))) AS conversion_contents,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.utm_term, '')), ''))) AS conversion_terms,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS conversion_referring_domains,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gclid, '')), ''))) AS conversion_gclids,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$fbclid, '')), ''))) AS conversion_fbclids,
+ arrayFilter(x -> notEmpty(toString(x)), groupArray(if(equals(event, 'test_event'), toString(ifNull(events.properties.$gad_source, '')), ''))) AS conversion_gad_sources,
+ arrayFilter(x -> greater(x, 0), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toUnixTimestamp(events.timestamp), 0))) AS utm_timestamps,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_campaign, '')), ''))) AS utm_campaigns,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_source, '')), ''))) AS utm_sources,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_medium, '')), ''))) AS utm_mediums,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_content, '')), ''))) AS utm_contents,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.utm_term, '')), ''))) AS utm_terms,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$referring_domain, '')), ''))) AS utm_referring_domains,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gclid, '')), ''))) AS utm_gclids,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$fbclid, '')), ''))) AS utm_fbclids,
+ arrayFilter(x -> notEmpty(x), groupArray(if(and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, '')))), toString(ifNull(events.properties.$gad_source, '')), ''))) AS utm_gad_sources
+ FROM
+ events
+ WHERE
+ or(and(equals(event, 'test_event'), greaterOrEquals(events.timestamp, toDateTime('2024-09-01 00:00:00')), lessOrEquals(events.timestamp, toDateTime('2024-10-31 23:59:59'))), and(equals(events.event, '$pageview'), notEmpty(toString(ifNull(events.properties.utm_campaign, ''))), notEmpty(toString(ifNull(events.properties.utm_source, ''))), greaterOrEquals(events.timestamp, minus(toDateTime('2024-09-01 00:00:00'), toIntervalSecond(7776000))), lessOrEquals(events.timestamp, toDateTime('2024-10-31 23:59:59'))))
+ GROUP BY
+ events.person_id
+ HAVING
+ greater(length(conversion_timestamps), 0))
+ ARRAY JOIN arrayEnumerate(conversion_timestamps) AS i)) AS attributed_conversions
+ GROUP BY
+ campaign,
+ id,
+ source) AS conv
GROUP BY
- campaign,
- id,
- source) AS conv
- GROUP BY
- conv.campaign,
- conv.id,
- conv.source)
- SELECT
- campaign_costs.id AS ID,
- campaign_costs.campaign AS Campaign,
- campaign_costs.source AS Source,
- round(campaign_costs.total_cost, 2) AS Cost,
- round(campaign_costs.total_clicks, 0) AS Clicks,
- round(campaign_costs.total_impressions, 0) AS Impressions,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
- round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
- round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
- round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
- round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`,
- ucg.conversion_0 AS `Sign Up Conversions`,
- round(divide(campaign_costs.total_cost, nullif(ucg.conversion_0, 0)), 2) AS `Cost per Sign Up Conversions`
- FROM
- campaign_costs
- LEFT JOIN ucg ON and(equals(campaign_costs.match_key, ucg.match_key), equals(campaign_costs.source, ucg.source))) AS previous_period ON and(equals(current_period.Campaign, previous_period.Campaign), equals(current_period.Source, previous_period.Source))
+ conv.campaign,
+ conv.id,
+ conv.source)
+ SELECT
+ campaign_costs.id AS ID,
+ campaign_costs.campaign AS Campaign,
+ campaign_costs.source AS Source,
+ round(campaign_costs.total_cost, 2) AS Cost,
+ round(campaign_costs.total_clicks, 0) AS Clicks,
+ round(campaign_costs.total_impressions, 0) AS Impressions,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
+ round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
+ round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
+ round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
+ round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`,
+ ucg.conversion_0 AS `Sign Up Conversions`,
+ round(divide(campaign_costs.total_cost, nullif(ucg.conversion_0, 0)), 2) AS `Cost per Sign Up Conversions`
+ FROM
+ campaign_costs
+ LEFT JOIN ucg ON and(equals(campaign_costs.match_key, ucg.match_key), equals(campaign_costs.source, ucg.source)))) AS combined
+ GROUP BY
+ combined.Campaign,
+ combined.Source
+ HAVING
+ greater(countIf(equals(combined._period, 'current')), 0)
ORDER BY
Cost DESC,
ID ASC
@@ -695,173 +777,210 @@
'query': '''
SELECT
- tuple(current_period.ID, previous_period.ID) AS ID,
- tuple(current_period.Campaign, previous_period.Campaign) AS Campaign,
- tuple(current_period.Source, previous_period.Source) AS Source,
- tuple(current_period.Cost, previous_period.Cost) AS Cost,
- tuple(current_period.Clicks, previous_period.Clicks) AS Clicks,
- tuple(current_period.Impressions, previous_period.Impressions) AS Impressions,
- tuple(current_period.CPC, previous_period.CPC) AS CPC,
- tuple(current_period.CTR, previous_period.CTR) AS CTR,
- tuple(current_period.`Reported Conversions`, previous_period.`Reported Conversions`) AS `Reported Conversions`,
- tuple(current_period.`Reported Conversion Value`, previous_period.`Reported Conversion Value`) AS `Reported Conversion Value`,
- tuple(current_period.`Reported ROAS`, previous_period.`Reported ROAS`) AS `Reported ROAS`,
- tuple(current_period.`Cost per Reported Conversions`, previous_period.`Cost per Reported Conversions`) AS `Cost per Reported Conversions`
+ tuple(anyIf(combined.ID, equals(combined._period, 'current')), anyIf(combined.ID, equals(combined._period, 'previous'))) AS ID,
+ tuple(anyIf(combined.Campaign, equals(combined._period, 'current')), anyIf(combined.Campaign, equals(combined._period, 'previous'))) AS Campaign,
+ tuple(anyIf(combined.Source, equals(combined._period, 'current')), anyIf(combined.Source, equals(combined._period, 'previous'))) AS Source,
+ tuple(anyIf(combined.Cost, equals(combined._period, 'current')), anyIf(combined.Cost, equals(combined._period, 'previous'))) AS Cost,
+ tuple(anyIf(combined.Clicks, equals(combined._period, 'current')), anyIf(combined.Clicks, equals(combined._period, 'previous'))) AS Clicks,
+ tuple(anyIf(combined.Impressions, equals(combined._period, 'current')), anyIf(combined.Impressions, equals(combined._period, 'previous'))) AS Impressions,
+ tuple(anyIf(combined.CPC, equals(combined._period, 'current')), anyIf(combined.CPC, equals(combined._period, 'previous'))) AS CPC,
+ tuple(anyIf(combined.CTR, equals(combined._period, 'current')), anyIf(combined.CTR, equals(combined._period, 'previous'))) AS CTR,
+ tuple(anyIf(combined.`Reported Conversions`, equals(combined._period, 'current')), anyIf(combined.`Reported Conversions`, equals(combined._period, 'previous'))) AS `Reported Conversions`,
+ tuple(anyIf(combined.`Reported Conversion Value`, equals(combined._period, 'current')), anyIf(combined.`Reported Conversion Value`, equals(combined._period, 'previous'))) AS `Reported Conversion Value`,
+ tuple(anyIf(combined.`Reported ROAS`, equals(combined._period, 'current')), anyIf(combined.`Reported ROAS`, equals(combined._period, 'previous'))) AS `Reported ROAS`,
+ tuple(anyIf(combined.`Cost per Reported Conversions`, equals(combined._period, 'current')), anyIf(combined.`Cost per Reported Conversions`, equals(combined._period, 'previous'))) AS `Cost per Reported Conversions`
FROM
- (WITH
- campaign_costs AS (
- SELECT
- campaign,
- id,
- source,
- any(match_key) AS match_key,
- sum(ifNull(toFloat(cost), 0)) AS total_cost,
- sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
- sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
- sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
- sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
- FROM
- (
- SELECT
- toString(campaign1) AS match_key,
- toString(campaign1) AS campaign,
- toString(campaign1) AS id,
- toString('Facebook Ads') AS source,
- toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
- toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
- toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
- toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
- 0 AS reported_conversion_value
- FROM
- `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
- WHERE
- and(greaterOrEquals(toDateTime(date1), toDateTime('2024-11-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-12-31 23:59:59')))
- UNION ALL
- SELECT
- toString(campaign2) AS match_key,
- toString(campaign2) AS campaign,
- toString(campaign2) AS id,
- toString('TikTok Ads') AS source,
- toFloat(coalesce(toFloat(impressions2), 0)) AS impressions,
- toFloat(coalesce(toFloat(clicks2), 0)) AS clicks,
- toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend2), 0))) AS cost,
- 0 AS reported_conversion,
- 0 AS reported_conversion_value
- FROM
- `bigquery.posthog_test.posthog_test_tiktok_ads_table` AS posthog_test_tiktok_ads_table
- WHERE
- and(greaterOrEquals(toDateTime(date2), toDateTime('2024-11-01 00:00:00')), lessOrEquals(toDateTime(date2), toDateTime('2024-12-31 23:59:59')))
- UNION ALL
- SELECT
- toString(campaign3) AS match_key,
- toString(campaign3) AS campaign,
- toString(campaign3) AS id,
- toString('LinkedIn Ads') AS source,
- toFloat(coalesce(toFloat(impressions3), 0)) AS impressions,
- toFloat(coalesce(toFloat(clicks3), 0)) AS clicks,
- toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend3), 0))) AS cost,
- 0 AS reported_conversion,
- 0 AS reported_conversion_value
- FROM
- `bigquery.posthog_test.posthog_test_linkedin_ads_table` AS posthog_test_linkedin_ads_table
- WHERE
- and(greaterOrEquals(toDateTime(date3), toDateTime('2024-11-01 00:00:00')), lessOrEquals(toDateTime(date3), toDateTime('2024-12-31 23:59:59'))))
- GROUP BY
- campaign,
- id,
- source)
+ (
SELECT
- campaign_costs.id AS ID,
- campaign_costs.campaign AS Campaign,
- campaign_costs.source AS Source,
- round(campaign_costs.total_cost, 2) AS Cost,
- round(campaign_costs.total_clicks, 0) AS Clicks,
- round(campaign_costs.total_impressions, 0) AS Impressions,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
- round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
- round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
- round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
- round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`
+ 'current' AS _period,
+ ID,
+ Campaign,
+ Source,
+ Cost,
+ Clicks,
+ Impressions,
+ CPC,
+ CTR,
+ `Reported Conversions`,
+ `Reported Conversion Value`,
+ `Reported ROAS`,
+ `Cost per Reported Conversions`
FROM
- campaign_costs) AS current_period
- LEFT JOIN (WITH
- campaign_costs AS (
- SELECT
- campaign,
- id,
- source,
- any(match_key) AS match_key,
- sum(ifNull(toFloat(cost), 0)) AS total_cost,
- sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
- sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
- sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
- sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
- FROM
- (
+ (WITH
+ campaign_costs AS (
SELECT
- toString(campaign1) AS match_key,
- toString(campaign1) AS campaign,
- toString(campaign1) AS id,
- toString('Facebook Ads') AS source,
- toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
- toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
- toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
- toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
- 0 AS reported_conversion_value
+ campaign,
+ id,
+ source,
+ any(match_key) AS match_key,
+ sum(ifNull(toFloat(cost), 0)) AS total_cost,
+ sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
+ sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
+ sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
+ sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
FROM
- `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
- WHERE
- and(greaterOrEquals(toDateTime(date1), toDateTime('2024-09-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-10-31 23:59:59')))
- UNION ALL
- SELECT
- toString(campaign2) AS match_key,
- toString(campaign2) AS campaign,
- toString(campaign2) AS id,
- toString('TikTok Ads') AS source,
- toFloat(coalesce(toFloat(impressions2), 0)) AS impressions,
- toFloat(coalesce(toFloat(clicks2), 0)) AS clicks,
- toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend2), 0))) AS cost,
- 0 AS reported_conversion,
- 0 AS reported_conversion_value
- FROM
- `bigquery.posthog_test.posthog_test_tiktok_ads_table` AS posthog_test_tiktok_ads_table
- WHERE
- and(greaterOrEquals(toDateTime(date2), toDateTime('2024-09-01 00:00:00')), lessOrEquals(toDateTime(date2), toDateTime('2024-10-31 23:59:59')))
- UNION ALL
- SELECT
- toString(campaign3) AS match_key,
- toString(campaign3) AS campaign,
- toString(campaign3) AS id,
- toString('LinkedIn Ads') AS source,
- toFloat(coalesce(toFloat(impressions3), 0)) AS impressions,
- toFloat(coalesce(toFloat(clicks3), 0)) AS clicks,
- toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend3), 0))) AS cost,
- 0 AS reported_conversion,
- 0 AS reported_conversion_value
- FROM
- `bigquery.posthog_test.posthog_test_linkedin_ads_table` AS posthog_test_linkedin_ads_table
- WHERE
- and(greaterOrEquals(toDateTime(date3), toDateTime('2024-09-01 00:00:00')), lessOrEquals(toDateTime(date3), toDateTime('2024-10-31 23:59:59'))))
- GROUP BY
- campaign,
- id,
- source)
+ (
+ SELECT
+ toString(campaign1) AS match_key,
+ toString(campaign1) AS campaign,
+ toString(campaign1) AS id,
+ toString('Facebook Ads') AS source,
+ toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
+ toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
+ toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
+ toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
+ 0 AS reported_conversion_value
+ FROM
+ `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
+ WHERE
+ and(greaterOrEquals(toDateTime(date1), toDateTime('2024-11-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-12-31 23:59:59')))
+ UNION ALL
+ SELECT
+ toString(campaign2) AS match_key,
+ toString(campaign2) AS campaign,
+ toString(campaign2) AS id,
+ toString('TikTok Ads') AS source,
+ toFloat(coalesce(toFloat(impressions2), 0)) AS impressions,
+ toFloat(coalesce(toFloat(clicks2), 0)) AS clicks,
+ toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend2), 0))) AS cost,
+ 0 AS reported_conversion,
+ 0 AS reported_conversion_value
+ FROM
+ `bigquery.posthog_test.posthog_test_tiktok_ads_table` AS posthog_test_tiktok_ads_table
+ WHERE
+ and(greaterOrEquals(toDateTime(date2), toDateTime('2024-11-01 00:00:00')), lessOrEquals(toDateTime(date2), toDateTime('2024-12-31 23:59:59')))
+ UNION ALL
+ SELECT
+ toString(campaign3) AS match_key,
+ toString(campaign3) AS campaign,
+ toString(campaign3) AS id,
+ toString('LinkedIn Ads') AS source,
+ toFloat(coalesce(toFloat(impressions3), 0)) AS impressions,
+ toFloat(coalesce(toFloat(clicks3), 0)) AS clicks,
+ toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend3), 0))) AS cost,
+ 0 AS reported_conversion,
+ 0 AS reported_conversion_value
+ FROM
+ `bigquery.posthog_test.posthog_test_linkedin_ads_table` AS posthog_test_linkedin_ads_table
+ WHERE
+ and(greaterOrEquals(toDateTime(date3), toDateTime('2024-11-01 00:00:00')), lessOrEquals(toDateTime(date3), toDateTime('2024-12-31 23:59:59'))))
+ GROUP BY
+ campaign,
+ id,
+ source)
+ SELECT
+ campaign_costs.id AS ID,
+ campaign_costs.campaign AS Campaign,
+ campaign_costs.source AS Source,
+ round(campaign_costs.total_cost, 2) AS Cost,
+ round(campaign_costs.total_clicks, 0) AS Clicks,
+ round(campaign_costs.total_impressions, 0) AS Impressions,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
+ round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
+ round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
+ round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
+ round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`
+ FROM
+ campaign_costs)
+ UNION ALL
SELECT
- campaign_costs.id AS ID,
- campaign_costs.campaign AS Campaign,
- campaign_costs.source AS Source,
- round(campaign_costs.total_cost, 2) AS Cost,
- round(campaign_costs.total_clicks, 0) AS Clicks,
- round(campaign_costs.total_impressions, 0) AS Impressions,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
- round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
- round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
- round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
- round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
- round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`
+ 'previous' AS _period,
+ ID,
+ Campaign,
+ Source,
+ Cost,
+ Clicks,
+ Impressions,
+ CPC,
+ CTR,
+ `Reported Conversions`,
+ `Reported Conversion Value`,
+ `Reported ROAS`,
+ `Cost per Reported Conversions`
FROM
- campaign_costs) AS previous_period ON and(equals(current_period.Campaign, previous_period.Campaign), equals(current_period.Source, previous_period.Source))
+ (WITH
+ campaign_costs AS (
+ SELECT
+ campaign,
+ id,
+ source,
+ any(match_key) AS match_key,
+ sum(ifNull(toFloat(cost), 0)) AS total_cost,
+ sum(ifNull(toFloat(clicks), 0)) AS total_clicks,
+ sum(ifNull(toFloat(impressions), 0)) AS total_impressions,
+ sum(ifNull(toFloat(reported_conversion), 0)) AS total_reported_conversions,
+ sum(ifNull(toFloat(reported_conversion_value), 0)) AS total_reported_conversion_value
+ FROM
+ (
+ SELECT
+ toString(campaign1) AS match_key,
+ toString(campaign1) AS campaign,
+ toString(campaign1) AS id,
+ toString('Facebook Ads') AS source,
+ toFloat(coalesce(toFloat(impressions1), 0)) AS impressions,
+ toFloat(coalesce(toFloat(clicks1), 0)) AS clicks,
+ toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend1), 0))) AS cost,
+ toFloat(coalesce(toFloat(conversions1), 0)) AS reported_conversion,
+ 0 AS reported_conversion_value
+ FROM
+ `bigquery.posthog_test.posthog_test_facebook_ads_table` AS posthog_test_facebook_ads_table
+ WHERE
+ and(greaterOrEquals(toDateTime(date1), toDateTime('2024-09-01 00:00:00')), lessOrEquals(toDateTime(date1), toDateTime('2024-10-31 23:59:59')))
+ UNION ALL
+ SELECT
+ toString(campaign2) AS match_key,
+ toString(campaign2) AS campaign,
+ toString(campaign2) AS id,
+ toString('TikTok Ads') AS source,
+ toFloat(coalesce(toFloat(impressions2), 0)) AS impressions,
+ toFloat(coalesce(toFloat(clicks2), 0)) AS clicks,
+ toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend2), 0))) AS cost,
+ 0 AS reported_conversion,
+ 0 AS reported_conversion_value
+ FROM
+ `bigquery.posthog_test.posthog_test_tiktok_ads_table` AS posthog_test_tiktok_ads_table
+ WHERE
+ and(greaterOrEquals(toDateTime(date2), toDateTime('2024-09-01 00:00:00')), lessOrEquals(toDateTime(date2), toDateTime('2024-10-31 23:59:59')))
+ UNION ALL
+ SELECT
+ toString(campaign3) AS match_key,
+ toString(campaign3) AS campaign,
+ toString(campaign3) AS id,
+ toString('LinkedIn Ads') AS source,
+ toFloat(coalesce(toFloat(impressions3), 0)) AS impressions,
+ toFloat(coalesce(toFloat(clicks3), 0)) AS clicks,
+ toFloat(convertCurrency('USD', 'USD', coalesce(toFloat(spend3), 0))) AS cost,
+ 0 AS reported_conversion,
+ 0 AS reported_conversion_value
+ FROM
+ `bigquery.posthog_test.posthog_test_linkedin_ads_table` AS posthog_test_linkedin_ads_table
+ WHERE
+ and(greaterOrEquals(toDateTime(date3), toDateTime('2024-09-01 00:00:00')), lessOrEquals(toDateTime(date3), toDateTime('2024-10-31 23:59:59'))))
+ GROUP BY
+ campaign,
+ id,
+ source)
+ SELECT
+ campaign_costs.id AS ID,
+ campaign_costs.campaign AS Campaign,
+ campaign_costs.source AS Source,
+ round(campaign_costs.total_cost, 2) AS Cost,
+ round(campaign_costs.total_clicks, 0) AS Clicks,
+ round(campaign_costs.total_impressions, 0) AS Impressions,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_clicks, 0)), 2) AS CPC,
+ round(multiply(divide(campaign_costs.total_clicks, nullif(campaign_costs.total_impressions, 0)), 100), 2) AS CTR,
+ round(campaign_costs.total_reported_conversions, 2) AS `Reported Conversions`,
+ round(campaign_costs.total_reported_conversion_value, 2) AS `Reported Conversion Value`,
+ round(divide(campaign_costs.total_reported_conversion_value, nullif(campaign_costs.total_cost, 0)), 2) AS `Reported ROAS`,
+ round(divide(campaign_costs.total_cost, nullif(campaign_costs.total_reported_conversions, 0)), 2) AS `Cost per Reported Conversions`
+ FROM
+ campaign_costs)) AS combined
+ GROUP BY
+ combined.Campaign,
+ combined.Source
+ HAVING
+ greater(countIf(equals(combined._period, 'current')), 0)
ORDER BY
Cost DESC,
ID ASC
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
index e0e59e7dd62f..7cb979866bfe 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_base_query_runner.py
@@ -50,6 +50,11 @@ logger = structlog.get_logger(__name__)
ResponseType = TypeVar("ResponseType", bound=AnalyticsQueryResponseProtocol)
+# Discriminator column tagging each row in the compare UNION ALL with its period.
+COMPARE_PERIOD_FIELD = "_period"
+COMPARE_PERIOD_CURRENT = "current"
+COMPARE_PERIOD_PREVIOUS = "previous"
+
class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC, Generic[ResponseType]):
"""Base class for marketing analytics query runners with shared functionality."""
@@ -955,6 +960,99 @@ class MarketingAnalyticsBaseQueryRunner(AnalyticsQueryRunner[ResponseType], ABC,
return [self._build_channel_type_expr()]
return [ast.Field(chain=[field]) for field in self.config.group_by_fields]
+ def _build_compare_pivot(
+ self,
+ current_period_query: ast.SelectQuery,
+ previous_period_query: ast.SelectQuery,
+ select_columns: list[ast.Expr],
+ key_columns: list[str],
+ ) -> ast.SelectQuery:
+ """Combine the two period queries with UNION ALL + a GROUP BY pivot instead of a LEFT JOIN.
+
+ ClickHouse runs a LEFT JOIN sequentially (build the right side, then probe the left); the
+ UNION ALL lets it run both period branches as concurrent pipelines. The pivot reproduces the
+ LEFT JOIN exactly:
+ - Each period query already emits one row per key, so `anyIf(col, _period=...)` picks that
+ single value.
+ - For a current row with no previous counterpart, `anyIf(col, _period='previous')` matches
+ no rows and returns the default of the column's type — '' / 0 for non-Nullable columns,
+ NULL for already-Nullable ones (CPC / CTR / ROAS). This is exactly what the LEFT JOIN
+ produces under ClickHouse's default `join_use_nulls = 0`, so reproducing it manually
+ (e.g. forcing NULL) would actually diverge from the join.
+ - `HAVING countIf(current) > 0` drops previous-only rows — matching the LEFT JOIN keeping
+ `current_period` as the left side.
+ The output tuples, aliases, order and limit are identical to the join form, so the ORDER BY
+ (over a current-period metric, expressed on the same tuple alias) and pagination are unchanged.
+
+ `key_columns` are the columns that uniquely identify a row — the same keys the old LEFT JOIN
+ matched on. Each runner passes the keys appropriate to its query shape.
+ """
+ column_aliases = [col.alias if isinstance(col, ast.Alias) else str(col) for col in select_columns]
+
+ def _labeled_period(period: str, period_query: ast.SelectQuery) -> ast.SelectQuery:
+ select: list[ast.Expr] = [
+ ast.Alias(alias=COMPARE_PERIOD_FIELD, expr=ast.Constant(value=period)),
+ *(ast.Field(chain=[alias]) for alias in column_aliases),
+ ]
+ return ast.SelectQuery(
+ select=select,
+ select_from=ast.JoinExpr(table=period_query),
+ )
+
+ union_query = ast.SelectSetQuery.create_from_queries(
+ [
+ _labeled_period(COMPARE_PERIOD_CURRENT, current_period_query),
+ _labeled_period(COMPARE_PERIOD_PREVIOUS, previous_period_query),
+ ],
+ "UNION ALL",
+ )
+ union_alias = "combined"
+
+ def _period_eq(period: str) -> ast.Expr:
+ return ast.CompareOperation(
+ left=ast.Field(chain=[union_alias, COMPARE_PERIOD_FIELD]),
+ op=ast.CompareOperationOp.Eq,
+ right=ast.Constant(value=period),
+ )
+
+ def _any_if(alias: str, period: str) -> ast.Expr:
+ return ast.Call(
+ name="anyIf",
+ args=[ast.Field(chain=[union_alias, alias]), _period_eq(period)],
+ )
+
+ # Build the pivot columns in the same order/alias as the join form.
+ pivot_columns: list[ast.Expr] = [
+ ast.Alias(
+ alias=alias,
+ expr=ast.Call(
+ name="tuple",
+ args=[_any_if(alias, COMPARE_PERIOD_CURRENT), _any_if(alias, COMPARE_PERIOD_PREVIOUS)],
+ ),
+ )
+ for alias in column_aliases
+ ]
+
+ group_by: list[ast.Expr] = [ast.Field(chain=[union_alias, key]) for key in key_columns]
+ having = ast.CompareOperation(
+ left=ast.Call(name="countIf", args=[_period_eq(COMPARE_PERIOD_CURRENT)]),
+ op=ast.CompareOperationOp.Gt,
+ right=ast.Constant(value=0),
+ )
+
+ select_from = ast.JoinExpr(table=union_query, alias=union_alias)
+ paginated = self._build_paginated_query(pivot_columns, select_from)
+ paginated.group_by = group_by
+ paginated.having = having
+ return paginated
+
+ def _build_paginated_query(
+ self, select_columns: list[ast.Expr], select_from: ast.JoinExpr | None, ctes=None
+ ) -> ast.SelectQuery:
+ """Build a paginated SelectQuery. Only the compare-capable table runners override this
+ (order-by / limit differ); the aggregated runner never builds a compare pivot."""
+ raise NotImplementedError
+
# Abstract methods that subclasses must implement
@abstractmethod
diff --git a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
index 452e65ccac76..da985dfc2fcf 100644
--- a/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/marketing_analytics_table_query_runner.py
@@ -79,7 +79,6 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
if isinstance(query, ast.SelectQuery)
else []
)
-
# Check if there are more results
has_more = len(results) > requested_limit
@@ -121,45 +120,24 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
right=ast.Field(chain=self.config.get_unified_conversion_field_chain(self.config.source_field)),
)
- def _build_compare_join(
- self, current_period_query: ast.SelectQuery, previous_period_query: ast.SelectQuery
- ) -> ast.JoinExpr:
- """Build the join expression for comparing current and previous periods.
-
- Join keys must uniquely identify a row at each drill-down level. Names alone
- don't satisfy this for ad-group / ad levels — two campaigns can both have an
- ad-group named "All Audiences", and renaming an entity between periods would
- appear as "deleted + created". So at AD_GROUP / AD we join by the platform ID
- + source. This assumes (AD_GROUP_ID, SOURCE) and (AD_ID, SOURCE) are unique
- per source — true for Meta; future adapters must preserve it or add campaign_id
- to the join.
+ def _get_compare_pivot_keys(self) -> list[str]:
+ """Columns that uniquely identify a row at the current drill-down level.
+
+ These are the keys the compare pivot groups by — the same keys the old
+ LEFT JOIN matched on. Names alone don't uniquely identify a row at ad-group /
+ ad levels (two campaigns can both have an ad-group named "All Audiences", and
+ renaming an entity between periods would appear as "deleted + created"), so at
+ AD_GROUP / AD we key by the platform ID + source. This assumes (AD_GROUP_ID,
+ SOURCE) and (AD_ID, SOURCE) are unique per source — true for Meta; future
+ adapters must preserve it or add campaign_id to the key.
"""
level = self.config.drill_down_level
campaign_alias = self.config.get_campaign_column_alias()
- def _eq(column: str) -> ast.CompareOperation:
- return ast.CompareOperation(
- left=ast.Field(chain=["current_period", column]),
- op=ast.CompareOperationOp.Eq,
- right=ast.Field(chain=["previous_period", column]),
- )
-
if level == MarketingAnalyticsDrillDownLevel.AD_GROUP:
- # Group-by key is (ad_group_id, source). Join on the same so renamed
- # ad-groups still match across periods.
- join_condition: ast.Expr = ast.And(
- exprs=[
- _eq(MarketingAnalyticsBaseColumns.AD_GROUP_ID.value),
- _eq(MarketingAnalyticsBaseColumns.SOURCE.value),
- ]
- )
+ return [MarketingAnalyticsBaseColumns.AD_GROUP_ID.value, MarketingAnalyticsBaseColumns.SOURCE.value]
elif level == MarketingAnalyticsDrillDownLevel.AD:
- join_condition = ast.And(
- exprs=[
- _eq(MarketingAnalyticsBaseColumns.AD_ID.value),
- _eq(MarketingAnalyticsBaseColumns.SOURCE.value),
- ]
- )
+ return [MarketingAnalyticsBaseColumns.AD_ID.value, MarketingAnalyticsBaseColumns.SOURCE.value]
elif level in (
MarketingAnalyticsDrillDownLevel.CHANNEL,
MarketingAnalyticsDrillDownLevel.SOURCE,
@@ -169,24 +147,10 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
):
# Repurposed-alias levels: campaign_alias holds the unique grouping value
# (channel type / source / utm value). Names are stable identifiers here.
- join_condition = _eq(campaign_alias)
+ return [campaign_alias]
else:
- # Campaign level joins on both Campaign + Source
- join_condition = ast.And(exprs=[_eq(campaign_alias), _eq(MarketingAnalyticsBaseColumns.SOURCE.value)])
-
- return ast.JoinExpr(
- table=current_period_query,
- alias="current_period",
- next_join=ast.JoinExpr(
- table=previous_period_query,
- alias="previous_period",
- join_type="LEFT JOIN",
- constraint=ast.JoinConstraint(
- expr=join_condition,
- constraint_type="ON",
- ),
- ),
- )
+ # Campaign level keys on both Campaign + Source.
+ return [campaign_alias, MarketingAnalyticsBaseColumns.SOURCE.value]
def _build_paginated_query(
self, select_columns: list[ast.Expr], select_from: ast.JoinExpr | None, ctes=None
@@ -242,28 +206,12 @@ class MarketingAnalyticsTableQueryRunner(MarketingAnalyticsBaseQueryRunner[Marke
previous_period_query = previous_runner.to_query()
current_period_query = self.to_query()
- # Create the join manually with proper AST structure
- join_expr = self._build_compare_join(current_period_query, previous_period_query)
-
# Get column names for the compare query
select_columns = self._get_filtered_select_columns(current_period_query)
- # Create tuple columns for comparison
- tuple_columns: list[ast.Expr] = [
- ast.Alias(
- alias=col.alias if isinstance(col, ast.Alias) else str(col),
- expr=ast.Call(
- name="tuple",
- args=[
- ast.Field(chain=["current_period", col.alias if isinstance(col, ast.Alias) else str(col)]),
- ast.Field(chain=["previous_period", col.alias if isinstance(col, ast.Alias) else str(col)]),
- ],
- ),
- )
- for col in select_columns
- ]
-
- return self._build_paginated_query(tuple_columns, join_expr)
+ return self._build_compare_pivot(
+ current_period_query, previous_period_query, select_columns, self._get_compare_pivot_keys()
+ )
def _build_select_columns_mapping(
self, conversion_aggregator: Optional[ConversionGoalsAggregator] = None
diff --git a/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py
index f964f61695fa..da3771ec18fb 100644
--- a/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/non_integrated_conversions_table_query_runner.py
@@ -201,67 +201,21 @@ class NonIntegratedConversionsTableQueryRunner(
modifiers=self.modifiers,
limit_context=self.limit_context,
)
+ # Share the prebuilt HogQL database across both periods so the compare query pays the ~1s
+ # Database.create_for once, not twice. Pre-populates the previous runner's cached_property.
+ previous_runner.__dict__["_shared_hogql_database"] = self._shared_hogql_database
previous_period_query = previous_runner.to_query()
current_period_query = self.to_query()
- join_expr = self._build_compare_join(current_period_query, previous_period_query)
select_columns = self._get_filtered_select_columns(current_period_query)
- tuple_columns: list[ast.Expr] = [
- ast.Alias(
- alias=col.alias if isinstance(col, ast.Alias) else str(col),
- expr=ast.Call(
- name="tuple",
- args=[
- ast.Field(chain=["current_period", col.alias if isinstance(col, ast.Alias) else str(col)]),
- ast.Field(chain=["previous_period", col.alias if isinstance(col, ast.Alias) else str(col)]),
- ],
- ),
- )
- for col in select_columns
+ # Keys are (Campaign, Source) — the same pair the old LEFT JOIN matched on.
+ key_columns = [
+ NonIntegratedConversionsColumnsSchemaNames.CAMPAIGN.value,
+ NonIntegratedConversionsColumnsSchemaNames.SOURCE.value,
]
-
- return self._build_paginated_query(tuple_columns, join_expr)
-
- def _build_compare_join(
- self, current_period_query: ast.SelectQuery, previous_period_query: ast.SelectQuery
- ) -> ast.JoinExpr:
- """Build the join expression for comparing current and previous periods"""
- return ast.JoinExpr(
- table=current_period_query,
- alias="current_period",
- next_join=ast.JoinExpr(
- table=previous_period_query,
- alias="previous_period",
- join_type="LEFT JOIN",
- constraint=ast.JoinConstraint(
- expr=ast.And(
- exprs=[
- ast.CompareOperation(
- left=ast.Field(
- chain=["current_period", NonIntegratedConversionsColumnsSchemaNames.CAMPAIGN.value]
- ),
- op=ast.CompareOperationOp.Eq,
- right=ast.Field(
- chain=["previous_period", NonIntegratedConversionsColumnsSchemaNames.CAMPAIGN.value]
- ),
- ),
- ast.CompareOperation(
- left=ast.Field(
- chain=["current_period", NonIntegratedConversionsColumnsSchemaNames.SOURCE.value]
- ),
- op=ast.CompareOperationOp.Eq,
- right=ast.Field(
- chain=["previous_period", NonIntegratedConversionsColumnsSchemaNames.SOURCE.value]
- ),
- ),
- ]
- ),
- constraint_type="ON",
- ),
- ),
- )
+ return self._build_compare_pivot(current_period_query, previous_period_query, select_columns, key_columns)
def _build_select_query(self, conversion_aggregator: Optional[ConversionGoalsAggregator] = None) -> ast.SelectQuery:
"""
diff --git a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
index a455f38ce2d0..9e8e0a41782c 100644
--- a/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
+++ b/products/marketing_analytics/backend/hogql_queries/test_marketing_analytics_table_query_runner.py
@@ -618,9 +618,9 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
]
)
def test_ad_levels_compare_join_uses_id(self, level, expected_id_column):
- """Compare mode at AD_GROUP / AD must join on the platform ID, not the name —
+ """Compare mode at AD_GROUP / AD must key the pivot on the platform ID, not the name —
otherwise two rows with the same ad-group / ad name across different campaigns
- would cross-product, and renames between periods would lose continuity.
+ would group together, and renames between periods would lose continuity.
"""
query = MarketingAnalyticsTableQuery(
dateRange=self.default_date_range,
@@ -638,30 +638,13 @@ class TestMarketingAnalyticsTableQueryRunner(ClickhouseTestMixin, BaseTest):
# to config. Avoids binding the test to the internal `_apply_drill_down_level`
# method name / call site.
runner.to_query()
- current = runner._build_main_select_query(conversion_aggregator=None)
- previous = runner._build_main_select_query(conversion_aggregator=None)
- join = runner._build_compare_join(current, previous)
-
- # Walk the join condition AST and collect every Field chain mentioned. The
- # AD_GROUP_ID / AD_ID column must appear — that's how we know we're joining
- # by the platform ID, not by the (ambiguous) name.
- constraint = join.next_join.constraint if join.next_join else None
- assert constraint is not None
- referenced_fields: list[str] = []
-
- def _collect_fields(node: ast.Expr) -> None:
- if isinstance(node, ast.Field) and node.chain:
- referenced_fields.append(str(node.chain[-1]))
- elif isinstance(node, ast.CompareOperation):
- _collect_fields(node.left)
- _collect_fields(node.right)
- elif isinstance(node, (ast.And, ast.Or)):
- for child in node.exprs:
- _collect_fields(child)
-
- _collect_fields(constraint.expr)
- assert expected_id_column.value in referenced_fields, (
- f"Expected compare join at {level} to reference {expected_id_column.value}, got fields: {referenced_fields}"
+ pivot_keys = runner._get_compare_pivot_keys()
+
+ # The compare pivot groups current/previous rows by these keys. The AD_GROUP_ID /
+ # AD_ID column must be among them — that's how we know we key by the platform ID,
+ # not by the (ambiguous) name.
+ assert expected_id_column.value in pivot_keys, (
+ f"Expected compare pivot at {level} to key on {expected_id_column.value}, got keys: {pivot_keys}"
)
@parameterized.expand(