Skip to content

Building multi-touch attribution on the GA4 export in SQL

Multi-touch attribution on the GA4 BigQuery export takes four SQL steps, each a table you can check. You build sessions with a channel, find conversions, collect touchpoints in a window, and split credit. On Google's public sample, January 2021, the result splits 1,115 conversions and loses no credit. It is the build behind our marketing attribution guide for GA4.

What does multi-touch attribution need from the GA4 export?

Multi-touch attribution needs three things per session from the GA4 export: a person, a channel, and a conversion. The person is user_pseudo_id, an identifier per browser or app instance. The session is that identifier plus the ga_session_id event parameter. One buyer on two devices is therefore two people with two shorter paths. The channel is the hard part. The export carries up to four traffic-source fields, and each answers a different question.

FieldScopeIn the public sampleUse for attribution
traffic_source (source, medium, name)User: the campaign that first acquired the userYesFirst acquisition only, never the session channel
source and medium event parametersEvent, inside event_paramsYesSession channel: first value seen in the session
collected_traffic_sourceEvent: UTM parameters and click IDs collected with the eventNoSession channel on recent exports, with gclid
session_traffic_source_last_clickSession: last-click source across Google Ads and manual campaignsNoReady-made session source for a last-click check

The sample predates the last two records, so every query here reads the event parameters. On a recent export, collected_traffic_source plays the same role with the same logic. Google's export schema documents all four fields. Traffic source in the GA4 export: four fields, one right answer per question compares them question by question.

A touchpoint is a session attributed to one channel and placed on a person's timeline by its first event. It is eligible for credit if it falls inside the lookback window of a later conversion.

A conversion path is the ordered list of a person's touchpoints that precede one conversion within the window, the converting session included.

One choice is fixed from the start. A session without any source counts as a direct touchpoint. Direct stays in the path and can receive credit. GA4 differs here: Google's documentation says its models credit direct only when the whole path is direct. Drop direct from mixed paths to mirror GA4.

Step 1: build the table of attributed sessions

The first step turns events into one row per session, labeled with the session's first medium value. A session without any medium parameter becomes Direct. Events without a ga_session_id are dropped, since they belong to no session. The grouping is one CASE expression, versioned with the query. It is the first thing to drift when campaign naming changes. The sample's obfuscated values, <Other> and (data deleted), fall into Other. A real property replaces them with campaign names that change every week.

WITH e AS (
  SELECT user_pseudo_id, event_timestamp,
    (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS sid,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'medium') AS medium,
    traffic_source.medium AS user_medium
  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20210101' AND '20210131'
),
s AS (
  SELECT user_pseudo_id, sid,
    COALESCE(ARRAY_AGG(medium IGNORE NULLS ORDER BY event_timestamp LIMIT 1)[SAFE_OFFSET(0)], '(none)') AS session_medium,
    LOGICAL_AND(medium IS NULL) AS no_medium_param,
    ANY_VALUE(user_medium) AS user_medium
  FROM e WHERE sid IS NOT NULL GROUP BY 1, 2
)
SELECT
  CASE session_medium
    WHEN '(none)' THEN 'Direct' WHEN 'organic' THEN 'Organic Search'
    WHEN 'cpc' THEN 'Paid Search' WHEN 'referral' THEN 'Referral'
    WHEN 'email' THEN 'Email' WHEN 'affiliate' THEN 'Affiliate' ELSE 'Other' END AS channel,
  COUNT(*) AS sessions,
  ROUND(100 * COUNT(*) / SUM(COUNT(*)) OVER (), 1) AS share_pct,
  COUNTIF(no_medium_param) AS no_medium_param,
  COUNTIF(session_medium != user_medium) AS differs_from_traffic_source
FROM s GROUP BY channel ORDER BY sessions DESC
ChannelSessionsShareNo medium parameterChannel differs from traffic_source
Direct46,31139.1%37,26728,435
Organic Search36,97531.2%014,911
Referral24,64720.8%014,422
Other7,7906.6%00
Paid Search1,7921.5%01
Affiliate7580.6%0758
Email1070.1%0107

Computed on 2026-10-15 on the public sample bigquery-public-data.ga4_obfuscated_sample_ecommerce (Google Merchandise Store, 2020-11-01 to 2021-01-31, obfuscated data).

The first trap is the direct session. On the sample, 37,267 of 46,311 direct sessions carry no medium parameter at all. Only 9,044 say (none) explicitly. A missing parameter can mean a typed URL, a lost consent, or a tracking gap. The export cannot tell them apart, so the rule has to be written down once.

The last column holds the second lesson. In January, 58,634 of 118,380 sessions (49.5%) differ from the user's traffic_source channel. Reading the user-level field as the session channel would rewrite half of the paths. If direct closing sessions bother you, last non-direct click handles them later, as a rule, without deleting touchpoints.

Linking conversions to touchpoints starts with the conversion unit. Each conversion is then joined to the same person's previous sessions. The unit matters on the public sample. January 2021 has 1,204 purchase events but only 894 distinct transaction IDs.

WITH p AS (
  SELECT user_pseudo_id, event_timestamp, ecommerce.transaction_id AS tid,
    (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS sid
  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20210101' AND '20210131' AND event_name = 'purchase'
),
by_tid AS (
  SELECT tid, COUNT(*) AS events FROM p GROUP BY tid
)
SELECT
  (SELECT COUNT(*) FROM p) AS purchase_events,
  (SELECT COUNT(DISTINCT CONCAT(user_pseudo_id, '-', CAST(sid AS STRING))) FROM p) AS purchase_sessions,
  (SELECT COUNT(*) FROM by_tid WHERE tid IS NOT NULL AND tid != '(not set)') AS distinct_transaction_ids,
  (SELECT SUM(events) FROM by_tid WHERE tid IS NULL OR tid = '(not set)') AS events_without_id,
  (SELECT COUNT(*) FROM by_tid WHERE tid != '(not set)' AND events > 1) AS ids_seen_twice_or_more,
  (SELECT COUNTIF(sid IS NULL) FROM p) AS purchases_without_session_id
Purchase eventsPurchase sessionsDistinct transaction IDsEvents without a usable IDIDs seen twice or morePurchases without a session ID
1,2041,115894300100

Computed on 2026-10-15 on the public sample bigquery-public-data.ga4_obfuscated_sample_ecommerce (Google Merchandise Store, 2020-11-01 to 2021-01-31, obfuscated data).

Counting events double-counts the 10 repeated transactions. Counting transaction IDs drops the 300 purchases without a usable ID. The purchase session avoids both traps: one session with a purchase is one conversion, here 1,115. The join then pairs each converting session with the same person's sessions inside the window.

A lookback window is the maximum delay between a touchpoint and a conversion for that touchpoint to receive credit. It is counted backward from the conversion.

WITH e AS (
  SELECT user_pseudo_id, event_timestamp, event_name,
    (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS sid,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'medium') AS medium
  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20201202' AND '20210131'
),
s AS (
  SELECT user_pseudo_id, sid, MIN(event_timestamp) AS started,
    LOGICAL_OR(event_name = 'purchase') AS converted,
    CASE COALESCE(ARRAY_AGG(medium IGNORE NULLS ORDER BY event_timestamp LIMIT 1)[SAFE_OFFSET(0)], '(none)')
      WHEN '(none)' THEN 'Direct' WHEN 'organic' THEN 'Organic Search'
      WHEN 'cpc' THEN 'Paid Search' WHEN 'referral' THEN 'Referral'
      WHEN 'email' THEN 'Email' WHEN 'affiliate' THEN 'Affiliate' ELSE 'Other' END AS channel
  FROM e WHERE sid IS NOT NULL GROUP BY 1, 2
),
w AS (
  SELECT * FROM UNNEST([
    STRUCT(7 AS days, DATE '2020-12-02' AS data_from), (14, DATE '2021-01-01'),
    (14, DATE '2020-12-02'), (30, DATE '2020-12-02')])
),
paths AS (
  SELECT w.days, w.data_from, c.user_pseudo_id, c.sid, COUNT(*) AS n,
    ARRAY_AGG(t.channel ORDER BY t.started LIMIT 1)[OFFSET(0)] AS first_channel
  FROM s AS c CROSS JOIN w JOIN s AS t
    ON t.user_pseudo_id = c.user_pseudo_id
   AND t.started BETWEEN c.started - w.days * 86400000000 AND c.started
   AND t.started >= UNIX_MICROS(TIMESTAMP(w.data_from))
  WHERE c.converted AND c.started >= UNIX_MICROS(TIMESTAMP '2021-01-01')
  GROUP BY 1, 2, 3, 4
)
SELECT days AS lookback_days, data_from, COUNT(*) AS conversions,
  COUNTIF(n > 1) AS multi_touch_paths, ROUND(AVG(n), 2) AS avg_touchpoints,
  COUNTIF(first_channel = 'Organic Search') AS organic_first_click
FROM paths GROUP BY 1, 2 ORDER BY 1, 2 DESC
Lookback windowData loaded fromConversionsMulti-touch pathsTouchpoints per pathOrganic Search, first click
7 days2020-12-021,1154821.87435
14 days2021-01-01 (January only)1,1155141.99440
14 days2020-12-021,1155362.05447
30 days2020-12-021,1156112.33454

Computed on 2026-10-15 on the public sample bigquery-public-data.ga4_obfuscated_sample_ecommerce (Google Merchandise Store, 2020-11-01 to 2021-01-31, obfuscated data).

The third trap is a data window as short as the conversion month. Loading only January's 31 days cuts 22 of 536 multi-touch paths at 14 days. Early-January buyers silently lose their December sessions. The rule: load one full lookback window before the first conversion. GA4's 90-day default is out of reach here, because the sample starts on November 1, 2020.

The window length moves credit, not only path counts. At 30 days, the sample finds 611 multi-touch paths instead of 536. Organic search's first-click credit rises from 447 to 454, because older Introducers enter the paths. Last click never moves with the window, since the closing touchpoint is always the converting session. Fix the window once, write it as a parameter, and keep it across months. The delay distribution in Time to conversion: how many days and sessions before a purchase helps size it.

Step 3: apply a rule: linear, position-based, or time decay

Applying a rule means computing each touchpoint's share of a conversion from its position, path length, and age. Three window functions provide all three inputs in one pass.

An attribution model is a rule that distributes the credit for one conversion across the touchpoints that preceded it. The credits of all touchpoints in a path sum to exactly one conversion, whatever the rule.

Linear gives 1 / n to each of the n touchpoints. Position-based gives 40% to the first and last touchpoints and shares 20% among the middle. It needs two special cases: one touchpoint takes everything, and two touchpoints take half each. Time decay weights each touchpoint by 0.5 to the power of its age in weeks. The weights are then divided by their sum within the path.

Timestamps in the export are microseconds, which explains the constants. The constant 604800e6 is one week, the seven-day half-life Google used in the retired model. The product 14 * 86400000000 is the 14-day window. The named WINDOW partitions by conversion, so each path is numbered and counted on its own.

WITH e AS (
  SELECT user_pseudo_id, event_timestamp, event_name,
    (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS sid,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'medium') AS medium
  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20201218' AND '20210131'
),
s AS (
  SELECT user_pseudo_id, sid, MIN(event_timestamp) AS started,
    LOGICAL_OR(event_name = 'purchase') AS converted,
    CASE COALESCE(ARRAY_AGG(medium IGNORE NULLS ORDER BY event_timestamp LIMIT 1)[SAFE_OFFSET(0)], '(none)')
      WHEN '(none)' THEN 'Direct' WHEN 'organic' THEN 'Organic Search'
      WHEN 'cpc' THEN 'Paid Search' WHEN 'referral' THEN 'Referral'
      WHEN 'email' THEN 'Email' WHEN 'affiliate' THEN 'Affiliate' ELSE 'Other' END AS channel
  FROM e WHERE sid IS NOT NULL GROUP BY 1, 2
),
tp AS (
  SELECT c.user_pseudo_id, c.sid AS conversion_sid, t.channel,
    ROW_NUMBER() OVER w AS pos, COUNT(*) OVER (PARTITION BY c.user_pseudo_id, c.sid) AS n,
    POW(0.5, (c.started - t.started) / 604800e6) AS decay
  FROM s AS c JOIN s AS t
    ON t.user_pseudo_id = c.user_pseudo_id
   AND t.started BETWEEN c.started - 14 * 86400000000 AND c.started
  WHERE c.converted AND c.started >= UNIX_MICROS(TIMESTAMP '2021-01-01')
  WINDOW w AS (PARTITION BY c.user_pseudo_id, c.sid ORDER BY t.started)
),
credits AS (
  SELECT *, 1 / n AS linear,
    CASE WHEN n = 1 THEN 1 WHEN n = 2 THEN 0.5
         WHEN pos IN (1, n) THEN 0.4 ELSE 0.2 / (n - 2) END AS position_based,
    decay / SUM(decay) OVER (PARTITION BY user_pseudo_id, conversion_sid) AS time_decay
  FROM tp
)
SELECT channel, ROUND(SUM(linear), 1) AS linear,
  ROUND(SUM(position_based), 1) AS position_based, ROUND(SUM(time_decay), 1) AS time_decay
FROM credits GROUP BY channel ORDER BY linear DESC
ChannelLinearPosition-basedTime decay
Referral574.4563.2580.5
Organic Search379.7390.4377.2
Direct84.483.881.7
Other63.364.162.4
Paid Search9.79.99.4
Email2.52.52.8
Affiliate1.01.01.0

Computed on 2026-10-15 on the public sample bigquery-public-data.ga4_obfuscated_sample_ecommerce (Google Merchandise Store, 2020-11-01 to 2021-01-31, obfuscated data). Rounded to one decimal.

The values match the six-model table of the attribution guide, run the same day on the same window. Position-based gives organic search 390.4 conversions, more than linear's 379.7. The gap comes from the 40% weight on Introducers, a role organic search plays often. Time decay favors referral, 580.5, because referral sessions sit close to the purchase. To attribute campaigns instead of channels, replace the channel CASE with the campaign parameter. The sample carries values such as NewYear_V1, and the other steps stay unchanged.

Step 4: give each touchpoint a role in the path

Each touchpoint of a multi-touch path plays one of three roles: Introducer, Influencer, or Closer. The Introducer is position 1, the Closer is the last position, and the Influencer is anything between. Single-touch paths get their own column, because every model agrees on them.

WITH e AS (
  SELECT user_pseudo_id, event_timestamp, event_name,
    (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS sid,
    (SELECT value.string_value FROM UNNEST(event_params) WHERE key = 'medium') AS medium
  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20201218' AND '20210131'
),
s AS (
  SELECT user_pseudo_id, sid, MIN(event_timestamp) AS started,
    LOGICAL_OR(event_name = 'purchase') AS converted,
    CASE COALESCE(ARRAY_AGG(medium IGNORE NULLS ORDER BY event_timestamp LIMIT 1)[SAFE_OFFSET(0)], '(none)')
      WHEN '(none)' THEN 'Direct' WHEN 'organic' THEN 'Organic Search'
      WHEN 'cpc' THEN 'Paid Search' WHEN 'referral' THEN 'Referral'
      WHEN 'email' THEN 'Email' WHEN 'affiliate' THEN 'Affiliate' ELSE 'Other' END AS channel
  FROM e WHERE sid IS NOT NULL GROUP BY 1, 2
),
tp AS (
  SELECT t.channel,
    ROW_NUMBER() OVER w AS pos, COUNT(*) OVER (PARTITION BY c.user_pseudo_id, c.sid) AS n
  FROM s AS c JOIN s AS t
    ON t.user_pseudo_id = c.user_pseudo_id
   AND t.started BETWEEN c.started - 14 * 86400000000 AND c.started
  WHERE c.converted AND c.started >= UNIX_MICROS(TIMESTAMP '2021-01-01')
  WINDOW w AS (PARTITION BY c.user_pseudo_id, c.sid ORDER BY t.started)
)
SELECT channel,
  COUNTIF(n = 1) AS single_touch,
  COUNTIF(n > 1 AND pos = 1) AS introducer,
  COUNTIF(n > 1 AND pos BETWEEN 2 AND n - 1) AS influencer,
  COUNTIF(n > 1 AND pos = n) AS closer
FROM tp GROUP BY channel ORDER BY single_touch + introducer DESC
ChannelSingle-touch pathsIntroducerInfluencer (touchpoints)Closer
Referral268220399356
Organic Search2521958997
Direct26798336
Other25365342
Paid Search5684
Email2001
Affiliate1000

Computed on 2026-10-15 on the public sample bigquery-public-data.ga4_obfuscated_sample_ecommerce (Google Merchandise Store, 2020-11-01 to 2021-01-31, obfuscated data).

The role table explains the gaps between models, as reading the gaps between five attribution models details. Organic search opens 195 multi-touch paths and closes only 97. Add its 252 single-touch paths to each, and you get first click, 447, and last click, 349. Direct opens 79 paths and closes 36. Keeping direct as a touchpoint reveals returning visitors who start paths.

The Influencer column counts touchpoints, not paths, since one channel can repeat in the middle of a path. Referral's 399 Influencer touchpoints include the store's own checkout domain, a self-referral defect. Roles come from the path, not from the model, so they stay stable when you switch rules. The sequences behind these roles are in Conversion paths: the channel sequences that end in a purchase.

Check: the sum of credits equals the conversions

Every rule gives each conversion a total credit of exactly one. Credits must therefore sum to the conversion count. The check compares that sum with an independent count of purchase sessions. It also counts paths whose credits drift from one.

WITH e AS (
  SELECT user_pseudo_id, event_timestamp, event_name,
    (SELECT value.int_value FROM UNNEST(event_params) WHERE key = 'ga_session_id') AS sid
  FROM `bigquery-public-data.ga4_obfuscated_sample_ecommerce.events_*`
  WHERE _TABLE_SUFFIX BETWEEN '20201218' AND '20210131'
),
s AS (
  SELECT user_pseudo_id, sid, MIN(event_timestamp) AS started,
    LOGICAL_OR(event_name = 'purchase') AS converted
  FROM e WHERE sid IS NOT NULL GROUP BY 1, 2
),
tp AS (
  SELECT c.user_pseudo_id AS u, c.sid AS cs,
    ROW_NUMBER() OVER (p ORDER BY t.started) AS pos, COUNT(*) OVER p AS n,
    POW(0.5, (c.started - t.started) / 604800e6)
      / SUM(POW(0.5, (c.started - t.started) / 604800e6)) OVER p AS time_decay
  FROM s AS c JOIN s AS t
    ON t.user_pseudo_id = c.user_pseudo_id
   AND t.started BETWEEN c.started - 14 * 86400000000 AND c.started
  WHERE c.converted AND c.started >= UNIX_MICROS(TIMESTAMP '2021-01-01')
  WINDOW p AS (PARTITION BY c.user_pseudo_id, c.sid)
),
per_conversion AS (
  SELECT u, cs, SUM(1 / n) AS linear, SUM(time_decay) AS time_decay,
    SUM(CASE WHEN n = 1 THEN 1 WHEN n = 2 THEN 0.5
             WHEN pos IN (1, n) THEN 0.4 ELSE 0.2 / (n - 2) END) AS position_based
  FROM tp GROUP BY 1, 2
)
SELECT
  (SELECT COUNTIF(converted AND started >= UNIX_MICROS(TIMESTAMP '2021-01-01')) FROM s) AS purchase_sessions,
  COUNT(*) AS paths,
  ROUND(SUM(linear), 6) AS linear_total,
  ROUND(SUM(time_decay), 6) AS time_decay_total,
  ROUND(SUM(position_based), 6) AS position_based_total,
  COUNTIF(GREATEST(ABS(linear - 1), ABS(time_decay - 1), ABS(position_based - 1)) > 1e-9) AS paths_not_summing_to_one
FROM per_conversion
Purchase sessionsPathsLinear totalTime decay totalPosition-based totalPaths not summing to one
1,1151,1151,115.01,115.01,115.00

Computed on 2026-10-15 on the public sample bigquery-public-data.ga4_obfuscated_sample_ecommerce (Google Merchandise Store, 2020-11-01 to 2021-01-31, obfuscated data).

The check catches the three bugs that attribution SQL usually ships with. A join on events instead of sessions multiplies rows, and the total climbs toward 1,204. A position-based rule without its two-touchpoint case gives 0.8 to those paths. A time decay without normalization gives more than one to every multi-touch path. Run the check after every load, as an assertion in Dataform or a test in dbt. A failed check should stop the refresh before any report reads the table. Rerun it whenever the window, the grouping, or the conversion unit changes. Each of those changes alters the paths, and only the sum proves nothing was lost.

FAQ

Do I need Python or machine learning for multi-touch attribution?

No, rule-based multi-touch attribution is arithmetic on ordered sessions, and BigQuery SQL covers it end to end. Window functions number the touchpoints, count path length, and normalize decay weights in one pass. Estimated models such as Markov chains or Shapley values are different. They need code outside SQL and far more paths per channel.

Why doesn't my SQL attribution match the GA4 interface?

Your SQL and the GA4 interface use different rules, windows, and identities. The interface reports "data-driven" or last click, with a 90-day default window for most key events. It applies its own channel grouping and reporting identity. Your SQL uses user_pseudo_id, your grouping, and your window. Reconcile last click first, then compare the other rules.

Should direct sessions receive attribution credit?

Keep direct sessions as touchpoints, then decide per model whether they keep credit. Deleting them shortens paths and hides that direct often opens one. On the public sample, January 2021, direct earns 62 conversions under last click. Under last non-direct click, GA4's rule, it earns 32: direct closing sessions pass to the previous touchpoint.

Can I attribute conversions to campaigns instead of channels?

Yes, the same four steps attribute conversions to campaigns instead of channels. Replace the channel expression with the campaign event parameter. On a recent export, collected_traffic_source.manual_campaign_name holds the same value. Expect thinner paths per campaign. Rerun the credit-sum check after the change, because campaign names drift faster than a channel grouping.

Does user_pseudo_id follow a buyer across devices?

No, user_pseudo_id identifies one browser or one app instance, not one person. A buyer who researches on a phone and pays on a laptop leaves two shorter paths. The user_id field links them only when your site sends a login identifier. Without it, multi-touch attribution undercounts long, cross-device paths and favors closing channels.

Keep the four steps and the check in one versioned query. The numbers then stay comparable month after month. Models, windows, and paths are compared side by side in Marketing attribution with GA4: the guide after the retired models. To run the same build on your own GA4 export, Book a diagnostic.

Sources