巢内array_to_json select语句PostgreSQL中
问题描述:
(ARRAY_AGG(row_to_json()))
我试图理解为什么这个工程:巢内array_to_json select语句PostgreSQL中
select
array_to_json(array_agg(row_to_json(positions_table)))
from (
select
sum(start_month),
function_id,
profile_id
from positions as subquery
group by function_id, profile_id
) as positions_table
但这并不:
select
profiles.id,
(array_to_json(array_agg(row_to_json(
select
sum(start_month),
function_id,
profile_id
from positions as subquery
group by function_id, profile_id
))))
from profiles
似乎就像我不允许select...
陈述在array_to_json(array_agg(row_to_json()))
之内,并且它需要引用一个表。
但我怀疑我可能失去了一些东西。
的错误是syntax error near select
。
答
您可以通过您的包裹子选择在括号内解决您的语法错误,但随后你会看到你的第二个错误; Postgres的将报告:
子查询必须返回只有一列
如果固定是错误你会看到:
列 “profiles.id” 必须出现在GROUP BY子句或在集合函数中使用
...正在接近第问题的真正原因。添加GROUP BY id
将得到的Postgres报告的根本原因:
多个由作为表达
功能row_to_json
期待一个单行子查询返回的行。
要聚合的配置文件ID的JSON摘要你必须执行连接。
SELECT
pr.id,
array_to_json(array_agg(row_to_json(positions_table.*)))
FROM profiles pr JOIN (
SELECT sum(start_month), function_id, profile_id
FROM positions
GROUP BY function_id, profile_id
) positions_table ON positions_table.profile_id = pr.id
GROUP BY pr.id
(可以删除从positions_table.*
的.*
,我只是增加了它的清晰度)。
FYI:与其做3个数据转换(JSON,数组,JSON),你应该使用'jsonb_agg()',而不是你一厢情愿的结果[查看更多](https://www.postgresql.org/docs/9.6/静态/功能-aggregate.html)。此外,'row_to_json'需要'record'作为输入,子查询不是它记录集的记录,所以你不能指望函数的目的是将1个单行转换成json来转换N行。 –