Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate a json object as key, value using postgres?

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?

like image 369
zola Avatar asked Mar 08 '23 13:03

zola


1 Answers

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;
like image 138
klin Avatar answered Mar 23 '23 13:03

klin