I'm relatively new to the concept of nested data and trying to get my head around the right way to flatten some GA data in BigQuery (https://support.google.com/analytics/answer/3437719?hl=en).
Now to give some context, for each visitor session I'm trying to capture the list of product SKUs that were looked at (detailed view) and if there was a transaction, the transaction id. By my reckoning, and after doing a bit of research, the simplest way to do this looks like this, using LEFT JOINS to bring back everything:
SELECT fullVisitorId as uId, visitId as vId, h.transaction.transactionId as
trId, STRING_AGG(p.productSKU, "|") as skus
FROM
`test-bigquery.12345678.ga_sessions_*` t
LEFT JOIN UNNEST(hits) h
LEFT JOIN UNNEST(h.product) p
WHERE
_TABLE_SUFFIX = '20170709'
AND h.eCommerceAction.action_type = '2'
GROUP BY uId, vId, trId
However, this appears to return zero results where trId is not null....
I then had a go at separating the above into two queries and joining. This seems to work and returns a seemingly sensible number of rows (~1000) where trId is not null.
WITH skus AS
(SELECT fullVisitorId as uId, visitId as vId, STRING_AGG(p.productSKU, "|") as skus
FROM
`test-bigquery.12345678.ga_sessions_*` t
LEFT JOIN UNNEST(hits) h
LEFT JOIN UNNEST(h.product) p
WHERE
_TABLE_SUFFIX = '20170709'
AND h.eCommerceAction.action_type = '2'
GROUP BY uId, vId),
transactions AS
(SELECT fullVisitorId as uId_trans, visitId as vId_trans, h.transaction.transactionId as trId
FROM
`test-bigquery.12345678.ga_sessions_*` t
LEFT JOIN UNNEST(hits) h
WHERE
_TABLE_SUFFIX = '20170709'
AND h.transaction.transactionId IS NOT NULL
GROUP BY uId_trans, vId_trans, trId)
SELECT skus.uId, skus.vId, transactions.trId, skus.skus
FROM skus
LEFT JOIN transactions ON transactions.vId_trans = skus.vId AND transactions.uId_trans = skus.uId
It would be awesome if someone could explain why the two don't give the same answer and hopefully equip me to get involved with all manner of nested fun in the future.... Thanks!