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?
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;
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With