从 JSON 数组连接列表
Concatenate list from JSON array
假设我在项目数据库中有 json:
第 1 行:
{"Id": "1", "Items": [{"Item": "Test Item", "Price": ".00"}, {"Item": "Test Item #2", "Price": ".00"}]}
第 2 行:
{"Id": "2", "Items": [{"Item": "Test Item #3", "Price": ".00"}, {"Item": "Test Item #1", "Price": ".00"}]}
我如何获得像这样格式化的行(|
是列分隔符):
1 | Test Item, Test Item #2
2 | Test Item #3, Test Item #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": ".00"}, {"Item": "Test Item #2", "Price": ".00"}]}')::json AS J
UNION all
SELECT ('{"Id": "2", "Items": [{"Item": "Test Item #3", "Price": ".00"}, {"Item": "Test Item #1", "Price": ".00"}]}')::json AS J
) T
) T
GROUP BY ID
假设我在项目数据库中有 json:
第 1 行:
{"Id": "1", "Items": [{"Item": "Test Item", "Price": ".00"}, {"Item": "Test Item #2", "Price": ".00"}]}
第 2 行:
{"Id": "2", "Items": [{"Item": "Test Item #3", "Price": ".00"}, {"Item": "Test Item #1", "Price": ".00"}]}
我如何获得像这样格式化的行(|
是列分隔符):
1 | Test Item, Test Item #2
2 | Test Item #3, Test Item #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": ".00"}, {"Item": "Test Item #2", "Price": ".00"}]}')::json AS J
UNION all
SELECT ('{"Id": "2", "Items": [{"Item": "Test Item #3", "Price": ".00"}, {"Item": "Test Item #1", "Price": ".00"}]}')::json AS J
) T
) T
GROUP BY ID