简体   繁体   English

如何在Postgres中的数组列中舍入每个数组元素?

[英]How to round each array element in an array column in Postgres?

Say I have a table results that contains a score column that is an array full of scores: 假设我有一个表格results ,其中包含一个score列,该列是一个充满分数的数组:

CREATE TABLE results (
  id serial PRIMARY KEY,
  scores numeric[]
);

I would like to update the table so that I round each score to 4 decimal places. 我想更新表格,以便将每个分数四舍五入到小数点后四位。

I have created a rounding function round_numeric_array that works for a single array value: 我创建了一个舍入函数round_numeric_array ,该函数可用于单个数组值:

CREATE OR REPLACE FUNCTION round_numeric_array (numeric[]) RETURNS numeric[]
LANGUAGE SQL
AS $$
   SELECT array_agg(round(unnest($1), 4))
$$;

But how do I apply it to every value in the table? 但是,如何将其应用于表中的每个值? I've been trying 我一直在尝试

UPDATE results SET scores = round_numeric_array(scores)

But I get a set-valued function called in context that cannot accept a set error. 但是我得到了一个set-valued function called in context that cannot accept a setset-valued function called in context that cannot accept a set错误。 Any ideas? 有任何想法吗?

Place the unnest() function in the FROM clause: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM