'SQL Pivot with GA4 Data in BigQuery
This is my original query using GA4 data in bigquery to understand the depth of engagement, looking at 01/22
SELECT active.num_days_active,
COUNT(DISTINCT active.user_id) AS num_users
FROM (
SELECT a.user_id, COUNT(DISTINCT a.event_date) AS num_days_active
FROM `test.events_202201*` a
WHERE _TABLE_SUFFIX >= '01' AND _TABLE_SUFFIX < '31'
AND stream_id = '1' OR stream_id = '2'
GROUP BY a.user_id) AS active
LEFT JOIN `test.events_202201*` a2 ON a2.user_id = active.user_id
WHERE a2._TABLE_SUFFIX >= '01' AND a2._TABLE_SUFFIX < '31'
GROUP BY active.num_days_active
ORDER BY active.num_days_active ASC;
It returns this, only showing a few rows but essentially counts the number of distinct days a user_id has had an event
| num_days_active | num_users |
|---|---|
| 1 | 36491 |
| 2 | 16428 |
| 3 | 9577 |
| ... | ... |
| 31 | 22 |
How would I pivot this, to show this for each month of this year - I can't seem to get my head round it. Would it need to be a dynamic pivot?
In the table schema event_date is a string.
I want to return the below table, for each month of the year
| num_days_active | January | February | ... |
|---|---|---|---|
| 1 | 36491 | 35211 | |
| 2 | 16428 | 13445 | |
| 3 | 9577 | 5000 | |
| ... | ... | ... | |
| 31 | 22 | 50 |
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
