2016-11-01 90 views
0

我在表中具有table_json以下記錄:的PostgreSQL 9.5:顯示JSON數據到表

id  doc 
    --------------------------------------- 
    1 
      {"name":"Shaw", 
       "address":{"line1":"L1", 
          "line2":"L2", 
          "zipcode":"12345" 
          } 
      } 

注:柱docjson類型。現在我想將json數據打印成以下格式的 。

預計輸出

id name address 
    -------------------------- 
    1 Shaw L1,L2,12345 
+1

你可以通過https://www.postgresql.org/docs/9.5/static/functions- json.html並相應地使用這些函數。 – Pragun

回答

3

使用json_each_text()橫向聯接:

with a_table (id, doc) as (
values 
(1, '{ 
    "name": "Shaw", 
    "address":{ 
     "line1":"L1", 
     "line2":"L2", 
     "zipcode":"12345" 
     } 
    }'::json) 
) 
select 
    id, 
    doc->>'name' as name, 
    string_agg(value, ',') as address 
from a_table, 
lateral json_each_text(doc->'address') 
group by 1, 2; 

id | name | address 
----+------+------------- 
    1 | Shaw | L1,L2,12345 
(1 row)