Skip to content

Instantly share code, notes, and snippets.

@JoaoCarabetta
Last active October 21, 2019 19:02
Show Gist options
  • Save JoaoCarabetta/fb9bfd1bf69f6c3f0fdb358b9b7cd632 to your computer and use it in GitHub Desktop.
Save JoaoCarabetta/fb9bfd1bf69f6c3f0fdb358b9b7cd632 to your computer and use it in GitHub Desktop.
Calculate mode in Athena SQL / Presto
/* It calculates the mode of a records-like `maintable`
*/
with counter as (
select
service,
array[
cast(row('Bob', count_if(name = 'Bob')) AS row(name varchar, age interger)),
cast(row('Alice', count_if(name = 'Alice')) AS row(name varchar, age interger)),
cast(row('Jane', count_if(name = 'Jane')) AS row(name varchar, age interger))
] as users
from maintable
group by service
)
select service, max_by(user.name, user.age) modal_name
from as_map, unnest(counter) t(user)
group by service
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment