Skip to content

Instantly share code, notes, and snippets.

@brito
Created May 23, 2020 02:13
Show Gist options
  • Save brito/8e5f9604cf8bb3a9928ca7e08f0c864a to your computer and use it in GitHub Desktop.
Save brito/8e5f9604cf8bb3a9928ca7e08f0c864a to your computer and use it in GitHub Desktop.
Top 10 count distinct values in a column
/*
Top 10 count distinct values in a column
eg */ select * from _meta (
'{app_public}',
'{data_report_session,data_raw_session,data_report}'),
_tally(_schema,_relname,_column);/*
*/
create function _tally(_schema name,_relname name,_column name)
returns table (_tally json) as $function_tally$
select xmltable.* from (select query_to_xml(format($$
select json_object_agg(coalesce(%3$I::text,'null'), count) as _tally
from (
select %3$I, count(*)
from %1$I.%2$I group by %3$I order by 2 desc
limit 10) c
$$,_schema,_relname,_column),false,false,'')) q,
xmltable('//table/row' passing query_to_xml columns _tally json)
$function_tally$ language sql stable;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment