简体   繁体   English

Postgres中数组聚合的算术运算

[英]Arithmetic operation on array aggregation in postgres

I have 2 questions regarding array_agg in postgres 我在postgres中有2个关于array_agg的问题

1) I have a column which is of type array_agg. 1)我有一列是array_agg类型。 I need to divide each of the element of the array_agg by a constant value. 我需要将array_agg的每个元素除以一个常量值。 Is it possible. 可能吗。 I checked http://www.postgresql.org/docs/9.1/static/functions-array.html , but could not find any reference to any arithmetic operations on array_agg. 我检查了http://www.postgresql.org/docs/9.1/static/functions-array.html ,但是找不到对array_agg上任何算术运算的引用。

Edit: An example of the desired operation. 编辑:所需操作的示例。

select array_agg(value)/2 from some_table

Here, I create an array of the column value from the table some_table and I have to divide each of the column by 4 在这里,我从some_table表创建一个列value的数组,我必须将每列除以4

2) Is it possible to use coalesce in array_agg. 2)是否可以在array_agg中使用合并。 In my scenario, there may be cases wherein, the array_agg of a column may result in a NULL array. 在我的情况下,可能存在列的array_agg可能导致NULL数组的情况。 Can we use coalesce for array_agg ? 我们可以对array_agg使用合并吗?

Example: 例:

select coalsece(array_agg(value1), 0)

Dividing is probably simper than you thought: 划分可能比您想象的要简单:

SELECT array_agg(value/2)
FROM ...

However, what value/2 does exactly depends on the data type. 但是, value/2作用完全取决于数据类型。 If value is an integer , fractional digits are truncated. 如果value是integer ,则小数位将被截断。 To preserve fractional digits use value/2.0 instead. 要保留小数位数,请改用value/2.0 The fractional digit forces the calculation to be done with numeric values. 小数位强制使用numeric值进行计算。

COALESCE won't make any difference outside the array. COALESCE在数组不会有任何区别。 Either there are no rows, then you get no result at all ('no row'), or if there are, you get an array, possibly with NULL elements. 要么没有行,要么根本没有结果(“没有行”),或者如果没有,则得到一个数组,可能带有NULL元素。 But the value of the array itself is never NULL . 但是数组本身的值永远不会为NULL

To replace individual NULL values with 0 : 0替换单个NULL值:

SELECT array_agg(coalesce(value/2.0, 0))
FROM ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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