2016-08-25 53 views
1

我有一個屬性表,其中一個屬性包含一個由11個數字元素組成的json數組。我需要對json數組中的數據進行一些聚合(沒有什麼花哨,只是平均數,最大/最小統計等)。解壓PostgreSQL中json列的數據

發現的廣義答案here看起來非常適合將數據重新格式化爲臨時視圖以進行快速查詢。我將jsonb_each更改爲son_each(也許這會起作用?),並且不返回任何錯誤,但最終會生成一個標題爲「create_jsonb_pivot_view」且沒有數據的單列。

下面是函數:

create or replace function create_jsonb_pivot_view 
    (table_name text, regular_columns text, json_column text) 
returns void language plpgsql as $$ 
declare 
    s text; 
begin 
    execute format ($fmt$ 
     select string_agg(format('%s->>''%s'' "%s"', key, key), ',') 
     from (
      select distinct key 
      from %s, json_each(%s) 
      order by 1 
      ) s; 
     $fmt$, json_column, '%s', '%s', table_name, json_column) 
    into s; 
    execute format(' 
     drop view if exists %s_view; 
     create view %s_view as 
     select %s, %s from %s', 
     table_name, table_name, regular_columns, s, table_name); 
end $$; 

最後是查詢使用的功能:

select create_jsonb_pivot_view('table', 'A, B, C, D', 'params') 

我以前從來沒有使用的功能在SQL所以這是我的一些新的領域。也許有一種不同的更好的方式來實現我的目標?

回答

0

沒關係實際工作 - 只花了一段時間來關閉功能。打算刪除我的帖子,但如果這對其他人有幫助,我會離開它!