PostgreSQL:如何根据阈值将文本字符串拆分为切片?

时间:2017-09-24 21:08:04

标签: python sql postgresql

我的PostgreSQL数据库中有一个示例数据,如下所示:

ID       Thresh    array
(int)    (int)     (text)
1        171       61,201,20.0
2        89        59,119,9.0

数组exaplanation如下:61, 201, 20.0 61 201和第二start values范围array20.0范围mean 。虽然arrayID的{​​{1}}值。对于每个array range,如果遇到阈值Thresh,我需要将ID Thresh array (int) (int) (text) 1 171 61,171,20.0,171,201,20.0 2 89 59,89,9.0,89,119,9.0 拆分为切片。如果它没有遇到阈值,那么输出将是相同的。预期产出如下:

array

虽然将20.0分割为9.0和{{1}}的平均值仍将保持不变。有人可以建议我怎样才能将数组范围拆分成片?

1 个答案:

答案 0 :(得分:2)

将字符串转换为数组,修改其元素(如有必要)并将数组转换回字符串:

with my_table(id, thresh, arr) as (
values
(1, 171, '61,201,20.0'),
(2, 89, '59,119,9.0')
)

select
    id, thresh,
    array_to_string(a, ',') as arr
from (
    select 
        id, thresh, 
        case 
            when thresh between a[1] and a[2] 
            then array[a[1], thresh, a[3], thresh, a[2], a[3]] 
            else a
        end as a
    from (
        select 
            id, thresh, 
            string_to_array(arr, ',')::float[] a
        from my_table
        ) s
    ) s;

 id | thresh |         arr          
----+--------+----------------------
  1 |    171 | 61,171,20,171,201,20
  2 |     89 | 59,89,9,89,119,9
(2 rows)