Given an array of text elements I'd like to calculate the number of occurrences and return them as a son object with a textual key and an integer value. (PostgreSQL 9.4)
Case 1 - without reference set
SELECT ARRAY['3G','2G','2G','3G','3G','3G','3G','4G']
should be transformed to
SELECT '{"2G": 2, "3G": 5, "4G": 1}'::jsonb
Case 2 - using a reference set
given a set of possible entries ARRAY['2G','3G','4G'], the returned json should also contain elements with a zero count.
SELECT ARRAY['3G','2G','2G','3G','3G','3G','3G']
should transform to
SELECT '{"2G": 2, "3G": 5, "4G": 0}'::jsonb
I got quite close on case 1 and 2 by using
-- case 1
SELECT json_object( array_agg(r.a)::text[],array_agg(r.num)::text[] )
FROM (
SELECT a, count(a) as num
FROM unnest( ARRAY['3G','2G','2G','3G','3G','3G','3G','4G'] ) a
GROUP BY a ORDER BY a
) r;
--case 2
SELECT json_object( array_agg(r.ref)::text[],array_agg(r.num)::text[] )
FROM (
SELECT ref, count(a) as num
FROM unnest( ARRAY['2G','3G','4G'] ) ref
LEFT JOIN unnest( ARRAY['3G','2G','2G','3G','3G','3G','3G'] ) a ON (ref = a)
GROUP BY ref ORDER BY ref
) r;
but, the result returns a textual value, eg:
SELECT '{"2G" : "2", "3G" : "5", "4G" : "0"}'::json -- case 2
Appreciate your help and feedback!
4GinARRAY['3G','2G','2G','3G','3G','3G','3G'].