0

PG_VERSION: 9.2

I have got a table with multiple boolean flags.

Eg:

id,flag1,flag2,flag3

Problem is, I want to get json array of these flags with its count like:

[{"title":"flag1","count":2},{"title":"flag2","count":3},{"title":"flag3","count":0}]

How to achieve this result? Tried this

    create or REPLACE function count_test(OUT json_string text) returns text
LANGUAGE plpgsql    AS $$
BEGIN    SELECT array_to_json(array_agg(rows))into json_string FROM ( select sum(case when flag1 then 1 else 0 end) as flag1,
sum(case when flag2 then 1 else 0 end) as flag2,
sum(case when flag3 then 1 else 0 end) as flag3 FROM flags
) rows;
  END;
$$;

but with this I can only get [{"flag1":2,"flag2":2,"flag3":0}]

Awaiting immediate response.

1
  • instead of case I'd rather cast flag1::int?.. so sum(flag1::int) looks more readable Commented Sep 11, 2017 at 7:15

1 Answer 1

1

you could aggregate row_to_json results to array and then try casting it to json and so on, but considering the very limited json support in 9.2 I'd just build json from string, eg:

postgres=# with flags(id,flag1,flag2) as (values(1,true,true),(2,false,true))
, s as (select sum(flag1::int) as f1, sum(flag1::int) as f2 from flags)
select concat('[{"title":"flag1","count":',f1,'},{"title":"flag2","count":',f2,'}]')::json from s;
                          concat
-----------------------------------------------------------
 [{"title":"flag1","count":1},{"title":"flag2","count":1}]
(1 row)
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.