PostgreSQL:替换数组元素中大于某个限制的值

时间:2017-06-11 13:29:31

标签: sql arrays postgresql replace conditional-statements

我的PostgreSQL 9.5数据库中有3行数组(类型,文本),如下所示:

ID     array
1      "112,292,19.3"
2      "203,383,22.1"
3      "136,226,18.9,286,346,27.1,346,406,6.5"

有些数组元素大于360.我想在if any array element > 360然后element - 360的条件下替换它们,以便替换的数组如下:

ID     array
1      "112,292,19.3"
2      "203,23,22.1"
3      "136,226,18.9,286,346,27.1,346,46,6.5"

如何替换大于360的值?

2 个答案:

答案 0 :(得分:3)

Postgres中有modulo operator %

with my_table(id, arr) as (
values
    (1, array[112,292,19.3]),
    (2, array[203,383,22.1]),
    (3, array[136,226,18.9,286,346,27.1,346,406,6.5])
)

select id, array_agg(unnest % 360 order by ordinality)
from my_table,
unnest(arr) with ordinality
group by 1;

 id |               array_agg                
----+----------------------------------------
  1 | {112,292,19.3}
  2 | {203,23,22.1}
  3 | {136,226,18.9,286,346,27.1,346,46,6.5}
(3 rows)

答案 1 :(得分:1)

尝试https://www.postgresql.org/docs/9.5/static/functions-math.html mod

  

y / x的剩余部分

例如:

x=# with a as (select * from unnest(array[136,226,18.9,286,346,27.1,346,46,6.5]) with ordinality a(i,o))
select array_agg(mod(i,360) order by o) from a;
               array_agg
----------------------------------------
 {136,226,18.9,286,346,27.1,346,46,6.5}
(1 row)