postgresql - 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
但我有一个对象数组
解决方案
回答:
WITH l AS (select distinct(column), count(*) from table group by column)
SELECT json_agg(json_build_object(column, count)) FROM l
推荐阅读
- python - 使用 Python3.x 中的格式在一个字符串中打印列表、字符串和字典
- java - 使用 JSoup 从 html 标签中获取正确的文本
- python - 如何用scrapy一次刮掉dt和dd
- django - 如何在 django 中以 ModelMultipleChoiceField 的形式获得不同的月份和年份?
- angular - ng-class 比较字符串
- scikit-learn - scikit-learn kmeans 聚类溢出错误
- css - CSS Flexbox:元素宽度
- javascript - 如何安排 javascript 对象以获得更好的性能
- solr - 在 Solr 中,“*”和“[* TO *]”有什么区别
- java - BackgroundPanel 我的背景图片覆盖了我的所有组件