Postgres:array_agg throws'无法累积空数组'用于空数组

时间:2017-04-18 12:41:55

标签: sql postgresql

当行包含空数组(array_agg)时使用{}时遇到问题。

这是我的SQL查询:

SELECT service_name, metric_name, array_agg(value_textarray)
FROM service_data
WHERE service_name = 'ActivityDataService'
GROUP BY service_name, metric_name

列定义如下:

service_name - text
metric_name - text
value_textarray - text[]

当我执行查询并且数据库中有空数组({})时,出现以下错误:

ERROR:  cannot accumulate empty arrays

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:7)

我有同样的问题,我无法过滤空数组,我发现这个函数解决了这个问题:

CREATE AGGREGATE array_accum (anyarray)
(
    sfunc = array_cat,
    stype = anyarray,
    initcond = '{}'
);  

来源:https://gist.github.com/ryandotsmith/4602274