I have a table with event data from Firebase in Google BigQuery with the following columns:
event_date, event_timestamp, event_name, (etc..).
To count the number of events by event_name I use the following query:
SELECT event_name, count(event_name) as event_count
FROM `analytics.events_20200510`
GROUP BY event_name;
which results in:
I want to convert this result to an array of structs, formatted as JSON. Example:
{
"events": [
{"first_open": 69},
{"screen_view": 510},
{"user_engagement": 354},
{"...": ..}
]
}
I started with
SELECT TO_JSON_STRING(
STRUCT(
??? as events
), true)
but I'm stuck and don't know what should go on the ??? to make it work. Any help would be highly appreciated.
Edit:
The answer below:
SELECT TO_JSON_STRING(
STRUCT(
(SELECT ARRAY (SELECT AS STRUCT event_name, count(*) AS count FROM `analytics.events_20200510` GROUP BY event_name)) AS events
), true);
results in
{
"events": [
{
"event_name": "session_start",
"count": 69
},
{
"event_name": "screen_view",
"count": 510
},
(...)
]
}
which is almost correct, but I would like the event names to be the 'key' and the count to be the 'value' in the struct (as in my JSON example). Would this be possible?
