2

我试试这个

select created_at, 
sum((json_array_elements(shipping_lines::json) ->> 'price')::float) as shipping_price
from t1
group by 1

它显示错误:

错误:聚合函数调用不能包含集合返回函数调用第 5 行:sum(((json_array_elements(shipping_lines::json) ->> 'price')... ^ 提示:您也许可以移动集合返回函数到 LATERAL FROM 项目中。

如何使用横向从解决此问题?我阅读了这个 PsSQL 文档,但不太了解横向函数

4

2 回答 2

4

那将是:

select t1.created_at, sum((x.obj->>'price')::float)  as shipping_price
from t1
left join lateral jsonb_array_element(t1.shipping_lines::jsonb) as x(obj) on true 
group by 1

或者,您可以计算sum()横向连接本身,这避免了外部聚合的需要(假设它created_at在表中是唯一的):

select t1.created_at, x.shipping_price
from t1
cross join lateral (
    select sum((x.obj->>'price')::float) as shipping_price
    from jsonb_array_elements(t1.shipping_lines::jsonb) as x(obj)
) x

请注意,我稍微更改了查询以使用jsonb而不是json:这种新数据类型比 更灵活和高效json(即使在这里不会产生真正的区别,只要有选择,它应该是首选)。

于 2020-10-28T10:38:13.597 回答
3

嗯。将逻辑移至from子句:

select created_at, sum( (j->>'price')::float) as shipping_price
from t1 left join lateral
     json_array_elements(shipping_lines::json) j
     on true
group by 1
于 2020-10-28T10:38:23.190 回答