【问题标题】:Extract elements from JSON array and return them as concatenated string从 JSON 数组中提取元素并将它们作为连接字符串返回
【发布时间】:2018-03-14 16:20:29
【问题描述】:

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 function 将“字母”值提取到数组中?

更新:

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

【问题讨论】:

    标签: postgresql jsonb postgresql-10 postgresql-json


    【解决方案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) 
    

    【讨论】:

    • 谢谢...为什么下面的工作不起作用? select string_agg( jsonb_array_elements( '[{"col": 7, "row": 12, "value": 3, "letter": "A"}, {"col": 8, "row": 12, "value": 10, "letter": "B"}]'::jsonb ) ->> 'letter', '' );
    • 使用集合返回函数作为聚合函数的参数是一个限制。在这种情况下,在 FROM 子句中使用 SRF,
    猜你喜欢
    • 2018-07-30
    • 2018-04-25
    • 1970-01-01
    • 2014-03-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-01
    • 1970-01-01
    相关资源
    最近更新 更多