-- subquery to define static and/or dynamic start and end date for the whole querywith date_range as (select'20211222'asstart_date, format_date('%Y%m%d',date_sub(current_date(), interval 1day)) as end_date),-- subquery to prepare and calculate engagement dataengagement as (selectcount(distinctcasewhen session_engaged ='1'thenconcat(user_pseudo_id,session_id) end) as engaged_sessions,sum(engagement_time_msec)/1000as engagement_time_seconds,count(distinctcasewhen session_engaged ='0'thenconcat(user_pseudo_id,session_id) end) as bouncesfrom (select user_pseudo_id, (select value.int_value from unnest(event_params) wherekey='ga_session_id') as session_id,max((select value.string_value from unnest(event_params) wherekey='session_engaged')) as session_engaged,max((select value.int_value from unnest(event_params) wherekey='engagement_time_msec')) as engagement_time_msecfrom-- change this to your google analytics 4 export location in bigquery`privat-327611.analytics_266663932.events_*`, date_rangewhere _table_suffix between date_range.start_date and date_range.end_dategroup by user_pseudo_id, session_id))-- main queryselect-- sessions (metric | the total number of sessions)count(distinctcasewhen event_name ='session_start'thenconcat(user_pseudo_id, cast(event_timestamp as string)) end) assessions,-- engaged sessions (metric | the number of sessions that lasted longer than 10 seconds, or had a conversion event, or had 2 or more screen or page views)max(engaged_sessions) as engaged_sessions,-- engagement rate (metric | the percentage of engaged sessions compared to all sessions) safe_divide(max(engaged_sessions),count(distinctcasewhen event_name ='session_start'thenconcat(user_pseudo_id, cast(event_timestamp as string)) end)) as engagement_rate,-- engagement time (metric | the average length of time in seconds that the app was in the foreground, or the web site had focus in the browser) safe_divide(max(engagement_time_seconds),max(engaged_sessions)) as engagement_time,-- bounces (metric | the total number of non-engaged sessions)max(bounces) as bounces,-- bounce rate (metric | bounces divided by total sessions) safe_divide(max(bounces),count(distinctcasewhen event_name ='session_start'thenconcat(user_pseudo_id, cast(event_timestamp as string)) end)) as bounce_rate,-- event count per session (metric | number of times an individual event (i.e. 'page_view') was triggered divided by all sessions) safe_divide(count(distinctcasewhen event_name ='page_view'thenconcat(user_pseudo_id, cast(event_timestamp as string)) end),count(distinctcasewhen event_name ='session_start'thenconcat(user_pseudo_id, cast(event_timestamp as string)) end)) as event_count_per_sessionfrom-- change this to your google analytics 4 export location in bigquery`privat-327611.analytics_266663932.events_*`, date_range, engagementwhere _table_suffix between date_range.start_date and date_range.end_date