0

PostgreSQL 10 表包含 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"
    }
]

如何仅提取“字母”值并将它们连接到一个字符串,如

ABCD

我想最后我应该使用ARRAY_TO_STRING函数,但是使用哪个JSON 函数将“字母”值提取到数组中?

更新:

在非常有用的 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;
4

1 回答 1

1

使用jsonb_array_elements()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) 
于 2018-03-14T16:27:49.977 回答