Skip to content

Instantly share code, notes, and snippets.

@samuelsimoes
Created November 21, 2015 18:20
Show Gist options
  • Save samuelsimoes/ce4ebf00fd1e708fd5e9 to your computer and use it in GitHub Desktop.
Save samuelsimoes/ce4ebf00fd1e708fd5e9 to your computer and use it in GitHub Desktop.
This function returns a JSON with the array's item ocurrence counting. It only works on Postgres >= 9.4
create function count_elements(text[]) returns json as $body$
select
json_object_agg(key, value)
from (
select
item as key,
count(*) as value
from (select unnest($1) item) as item
group by item
) agg;
$body$
language sql;
select count_elements(array['foo', 'foo', 'bar']);
-- { "foo" : 2, "bar" : 1 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment