从 JSON 数组中提取元素并将它们 return 作为连接字符串

Extract elements from JSON array and return them as concatenated string

PostgreSQL 10 table 包含 JSON 数据,例如(这里是 SQL Fiddle):

[
    {
        "col": 7,
        "row": 12,
        "value": 3,
        "letter": "A"
    },
    {
        "col": 8,
        "row": 12,
        "value": 10,
        "letter": "B"
    },
    {
        "col": 9,
        "row": 12,
        "value": 1,
        "letter": "C"
    },
    {
        "col": 10,
        "row": 12,
        "value": 2,
        "letter": "D"
    }
]

如何仅提取 "letter" 值并将它们连接成类似

的字符串
ABCD

我想最后我应该使用 ARRAY_TO_STRING function, but which JSON function 来将 "letter" 值提取到数组中吗?

更新:

在非常有用的 PostgreSQL 邮件列表中也得到了提示:

SELECT string_agg(x->>'letter','') FROM json_array_elements(

'[{"col": 7, "row": 12, "value": 3, "letter": "A"}, {"col": 8, "row": 12, "value": 10, "letter": "B"}, {"col": 9, "row": 12, "value": 1, "letter": "C"}, {"col": 10, "row": 12, "value": 2, "letter": "D"}]'::json

) x;

使用jsonb_array_elements() and string_agg():

with my_table(json_data) as (
values(
'[
    {
        "col": 7,
        "row": 12,
        "value": 3,
        "letter": "A"
    },
    {
        "col": 8,
        "row": 12,
        "value": 10,
        "letter": "B"
    },
    {
        "col": 9,
        "row": 12,
        "value": 1,
        "letter": "C"
    },
    {
        "col": 10,
        "row": 12,
        "value": 2,
        "letter": "D"
    }
]'::jsonb)
)
select string_agg(value->>'letter', '')
from my_table
cross join lateral jsonb_array_elements(json_data)

 string_agg 
------------
 ABCD
(1 row)