Skip to content
Advertisement

Standard SQL – How to count frequency of values in array

I get the following Table with the query underneath:

result of SQL query - screenshot

For each of the values in the trafic_medium column (e.g.: cpc, referral, organic, etc.) I am trying to figure out how often each value occurred in the array, so preferably add a new column ‘count’ that shows ho often that value occurred?

I’m new to SQL so I’m quite stuck.

I tried this so far:

Based on this thread: How to count frequency of elements in a bigquery array field

However this only shows the number of ‘Any_Value not for all distinct.

I would appreciate some help!

p.s. I am doing this in BigQuery on the ‘bigquery-public-dataset.google_analytics_sample’

Advertisement

Answer

Below is for BigQuery Standard SQL to help you get started

if to apply to sample/dummy data from you question as in below example

result will be

enter image description here

As an option – you can use below version

which (if to apply to the same dummy data) will output below

enter image description here

This version looks more aligned with your expected result

Advertisement