2017-09-24 61 views
0

我在我的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和第二201start和結束的array範圍values。而20.0arraymean值。對於每個ID,如果遇到閾值Thresh,我需要將array range分割成片。如果它沒有遇到閾值,那麼輸出將是相同的。預期的輸出如下所示:

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 

雖然,例如20.0分裂array平均值和9.0將保持不變。有人可以建議我如何將陣列區域分割成片?

+0

告訴我們,你至今嘗試過的代碼,請。這可能比你的英文解釋更清楚。另外,如果可以查詢數據庫,處理文本並報告結果,請爲'python'或類似內容添加標籤。限制SQL解決方案可能比你想要的更緊縮。 –

+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)