6

I am trying to extract some statistical data from my database. I have an _employees table and I want to get employee count by country. Suppose _employees table has a column country and I have this query for a key-value representation of an aggregate count.

select json_object_agg(key, value) 
from (
        select distinct e.country 
        from _employees as e group by (e.country)
    ) as key, 
    (
        select distinct count(1) 
        from _employees as e 
        group by(e.country)
    ) as value;

I want the data like this

{
     "ET": 100,
     "JM": 245 // And it will go on like this
}

but I've got the following error

key value must be scalar, not array, composite, or json.

Can this be done? Is there a better way to go about this?

1 Answer 1

11

In the inner query select countries with the number of employees in each country:

select json_object_agg(country, count)
from (
    select country, count(*)
    from _employees
    group by 1
    ) s;
Sign up to request clarification or add additional context in comments.

Comments

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.