假设我在项目数据库中有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
答案 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