来自JSON数组的连接列表

时间:2015-12-03 18:26:15

标签: postgresql postgresql-json

假设我在项目数据库中有json:

ROW1:

{"Id": "1", "Items": [{"Item": "Test Item", "Price": "$5.00"}, {"Item": "Test Item #2", "Price": "$15.00"}]}

行2:

{"Id": "2", "Items": [{"Item": "Test Item #3", "Price": "$1.00"}, {"Item": "Test Item #1", "Price": "$4.00"}]}

如何获得这样格式化的行(|是列分隔符):

1 | Test Item, Test Item #2
2 | Test Item #3, Test Item #1

1 个答案:

答案 0 :(得分:1)

SELECT  ID || '|' || ARRAY_TO_STRING( ARRAY_AGG( ITEMS ), ', ')
FROM
    (
        SELECT T.J->>'Id' AS ID, json_array_elements((T.J->'Items')::json)->>'Item' AS ITEMS
        FROM
        (
            SELECT ('{"Id": "1", "Items": [{"Item": "Test Item", "Price": "$5.00"}, {"Item": "Test Item #2", "Price": "$15.00"}]}')::json AS J
            UNION all
            SELECT ('{"Id": "2", "Items": [{"Item": "Test Item #3", "Price": "$1.00"}, {"Item": "Test Item #1", "Price": "$4.00"}]}')::json AS J
        ) T
    ) T
GROUP   BY ID