【问题标题】:Sum of string integers in array - Postgres数组中字符串整数的总和 - Postgres
【发布时间】:2021-06-16 19:18:01
【问题描述】:

在 postgres DB 中,我有一个 jsonb 列,其中包含字符串数组中的数据,例如:

{
 "name": "john doe",
 "testData": "["1", "2", "3", "", "", ""]"
}

我想将字符串 testData 转换为数组,然后将这些字符串整数转换为 int,然后将它们相加。

select sum(ARRAY(test_column->>'testData')::int) as sum from table;

Output -> "6"

【问题讨论】:

    标签: sql postgresql postgresql-9.5


    【解决方案1】:

    如果您的 JSON 格式正确,那么您可以提取数组并对非空值求和:

    select *
    from t cross join lateral
         (select sum(nullif(el, '')::int)
          from jsonb_array_elements_text(t.x->'testData') el
         ) s;
    

    Here 是一个 dbfiddle。

    请注意,您将数据结构描述为“字符串数组”。但是你有一组额外的引号,所以它实际上是“一个看起来像字符串数组的字符串”。

    【讨论】:

    • 没错@Gordon_Linoff,它是看起来像字符串数组的字符串。我刚刚检查了你的小提琴,你可能需要以这种形式插入 testData:"["1", "2"....]"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-03
    • 1970-01-01
    • 2020-01-18
    • 2013-01-11
    • 1970-01-01
    相关资源
    最近更新 更多