Created
November 21, 2015 18:20
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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