如何解决如何将设置返回功能从PostgreSQL移至LATERAL
我尝试
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)->> '价钱')... ^提示:您也许可以将返回设置的函数移至LATERAL FROM项中。
如何使用“横向发件人”解决此问题?我读过this PsSQL docs,但不太了解横向功能
解决方法
那将是:
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
更加灵活和高效(即使不会产生真正的变化)在这里,只要有选择就应该首选)。
嗯。将逻辑移至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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。