首页 > 解决方案 > postgresql,将结果表作为json对象获取

问题描述

给定这个查询:

select distinct(column), count(*) from table group by column;

返回这些结果:

column|count
------|-----
id1   |1
id2   |5
...

我想用这个结构获得结果为json:

{ 
  "id1":1,
  "id2":5
}

我应该看哪些 postgresql json 函数?我试过了


select array_to_json(array_agg(row_to_json(t)))
from(
select  distinct(column), count(*) from table group by column
) t

但我有一个对象数组

标签: postgresql

解决方案


回答:

WITH l AS (select distinct(column), count(*) from table group by column)
SELECT json_agg(json_build_object(column, count)) FROM l

推荐阅读