PG_VERSION:9.2
我有一个包含多个布尔标志的表。
例如:
id,flag1,flag2,flag3
问题是,我想得到这些标志的json数组,其计数如下:
[{"title":"flag1","count":2},{"title":"flag2","count":3},{"title":"flag3","count":0}]
如何实现这一结果?试过这个
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;
$$;
但有了这个,我才能得到
[{"flag1":2,"flag2":2,"flag3":0}]
等待立即回复。
答案 0 :(得分:1)
你可以将row_to_json
结果聚合到数组然后尝试将其转换为json,依此类推,但考虑到9.2中的json支持非常有限,我只需从字符串构建json,例如:
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)