SELECT
fullVisitorId,
transactionId,
first_sourceMedium,
last_sourceMedium
FROM (
SELECT
fullVisitorId,
transactionId,
NTH_VALUE(trafficSource.source + " / " + trafficSource.medium, 1)
OVER (
PARTITION BY fullVisitorId
ORDER BY visitStartTime
RANGE BETWEEN 30 * 24 * 60 * 60 PRECEDING AND CURRENT ROW -- Lookback Window: 30 days
) as first_sourceMedium,
(trafficSource.source + " / " + trafficSource.medium) as last_sourceMedium,
FROM
(
SELECT
fullVisitorId,
visitStartTime,
SPLIT(GROUP_CONCAT(hits.transaction.transactionId)) as transactionId,
trafficSource.source,
trafficSource.medium
FROM
TABLE_DATE_RANGE([75923065.ga_sessions_], TIMESTAMP('2014-05-29'), TIMESTAMP('2014-06-30')) -- Analysis Window
GROUP EACH BY fullVisitorId, visitStartTime, trafficSource.source, trafficSource.medium
)
)
WHERE
NOT transactionId IS NULL
GROUP BY 1,2,3,4