postgresql 9.2 - Postgres: How to get json array of multiple boolean columns? -
pg_version: 9.2
i have got table multiple boolean flags.
eg:
id,flag1,flag2,flag3 problem is, want json array of these flags count like:
[{"title":"flag1","count":2},{"title":"flag2","count":3},{"title":"flag3","count":0}] how achieve result? tried
create or replace function count_test(out json_string text) returns text language plpgsql $$ begin select array_to_json(array_agg(rows))into json_string ( select sum(case when flag1 1 else 0 end) flag1, sum(case when flag2 1 else 0 end) flag2, sum(case when flag3 1 else 0 end) flag3 flags ) rows; end; $$; but can [{"flag1":2,"flag2":2,"flag3":0}]
awaiting immediate response.
you aggregate row_to_json results array , try casting json , on, considering limited json support in 9.2 i'd build json string, eg:
postgres=# flags(id,flag1,flag2) (values(1,true,true),(2,false,true)) , s (select sum(flag1::int) f1, sum(flag1::int) f2 flags) select concat('[{"title":"flag1","count":',f1,'},{"title":"flag2","count":',f2,'}]')::json s; concat ----------------------------------------------------------- [{"title":"flag1","count":1},{"title":"flag2","count":1}] (1 row)
Comments
Post a Comment