2

I have a table that has data like:

id, array_json
123, [{"Name": "John", "Age": "12"}, {"Name": "Jane", "Age": "18"}, {"Name": "Jake", "Age": "34"}]
124, [{"Name": "Dolly", "Age": "12"}, {"Name": "Molly", "Age": "18"}, {"Name": "Rosa", "Age": "34"}]
123, []
125, [{"Name": "Dolly", "Age": "12"}, {"Name": "Dolly", "Age": "18"}, {"Name": "Holt", "Age": "34"}]

Its basically an id mapped to an array of jsons, which is a jsonb. I want the output to be all the unique names (Key is "Name") & their count as follows:

id, Unique_Names, Count
123, ["John", "Jane", "Jake"], 3
124, ["Dolly", "Molly", "Rosa"], 3
125, [], 0
126, ["Dolly", "Holt"], 2

How do I do this in postgres?

3
  • I cannot understand, why do you save JSON data into a postgresql field (?) while there are function in control language (e.g. php) to convert JSON <-> arrray (!). Postgresql does have string function, but it is definitely not a language mainly for string manipulation. Commented Jan 31, 2020 at 8:35
  • @schweik Postgres has a jsonb type which is essentially to store jsons. Commented Jan 31, 2020 at 8:37
  • It is your decision, but not an answer to my question. In case you need to store JSON data only, you found a perfect solution, but if you want to analyse the dadta stored in JSON object, I recommend to take a standard way. Howg Commented Jan 31, 2020 at 9:03

1 Answer 1

4

You need to unnest and then aggregate back:

select t2.id
       t2.names as unique_names, 
       jsonb_array_length(names) as count 
from (
  select t.id, 
         (select jsonb_agg(distinct e.val ->> 'Name' order by e.val ->> 'Name') 
          from jsonb_array_elements(t.array_json) as e(val)) as names
  from the_table t
) AS t2
order by t2.id;

Online example

Sign up to request clarification or add additional context in comments.

1 Comment

Wrap it as a subquery to get the Count column

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.