![](/img/trans.png)
[英]Postgres: How to alter jsonb value type for each element in an array?
[英]How to round each array element in an array column in Postgres?
假设我有一个表格results
,其中包含一个score
列,该列是一个充满分数的数组:
CREATE TABLE results (
id serial PRIMARY KEY,
scores numeric[]
);
我想更新表格,以便将每个分数四舍五入到小数点后四位。
我创建了一个舍入函数round_numeric_array
,该函数可用于单个数组值:
CREATE OR REPLACE FUNCTION round_numeric_array (numeric[]) RETURNS numeric[]
LANGUAGE SQL
AS $$
SELECT array_agg(round(unnest($1), 4))
$$;
但是,如何将其应用于表中的每个值? 我一直在尝试
UPDATE results SET scores = round_numeric_array(scores)
但是我得到了一个set-valued function called in context that cannot accept a set
的set-valued function called in context that cannot accept a set
错误。 有任何想法吗?
将unnest()
函数放在FROM子句中:
CREATE OR REPLACE FUNCTION round_numeric_array (numeric[])
RETURNS numeric[]
LANGUAGE SQL
AS $$
SELECT array_agg(round(arr, 4))
FROM unnest($1) as arr;
$$;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.