简体   繁体   中英

Arithmetic operation on array aggregation in postgres

I have 2 questions regarding array_agg in postgres

1) I have a column which is of type array_agg. I need to divide each of the element of the array_agg by a constant value. 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.

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

2) Is it possible to use coalesce in array_agg. In my scenario, there may be cases wherein, the array_agg of a column may result in a NULL array. Can we use coalesce for 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. If value is an integer , fractional digits are truncated. To preserve fractional digits use value/2.0 instead. The fractional digit forces the calculation to be done with numeric values.

COALESCE won't make any difference outside the array. 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. But the value of the array itself is never NULL .

To replace individual NULL values with 0 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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