gpt4 book ai didi

postgresql - 数组类型的 array_agg

转载 作者:行者123 更新时间:2023-11-29 11:11:19 24 4
gpt4 key购买 nike

我正在尝试让 array_agg 与 Postgresql 中的数组类型一起工作,但我无法弄清楚这是否可行,如果可行,该怎么做。我查询的相关部分如下所示:

array_agg(ARRAY[e.alert_type::text, e.id::text, cast(extract(epoch from e.date_happened) as text)] order by e.date_happened asc, e.id asc)

我得到的响应错误是ERROR: could not find array type for data type text[]

这是可能的还是我应该尝试寻找另一种方法?

谢谢!

最佳答案

您可以编写自定义聚合来处理您的特定数组数组,例如:

DROP TABLE IF EXISTS e;
CREATE TABLE e
(
id serial PRIMARY KEY,
alert_type text,
date_happened timestamp with time zone
);

INSERT INTO e(alert_type, date_happened) VALUES
('red', '2011-05-10 10:15:06'),
('yellow', '2011-06-22 20:01:19');

CREATE OR REPLACE FUNCTION array_agg_custom_cut(anyarray)
RETURNS anyarray
AS 'SELECT $1[2:array_length($1, 1)]'
LANGUAGE SQL IMMUTABLE;

DROP AGGREGATE IF EXISTS array_agg_custom(anyarray);
CREATE AGGREGATE array_agg_custom(anyarray)
(
SFUNC = array_cat,
STYPE = anyarray,
FINALFUNC = array_agg_custom_cut,
INITCOND = $${{'', '', ''}}$$
);

查询:

SELECT
array_agg_custom(
ARRAY[
alert_type::text,
id::text,
CAST(extract(epoch FROM date_happened) AS text)
])
FROM e;

结果:

              array_agg_custom              
--------------------------------------------
{{red,1,1305036906},{yellow,2,1308787279}}
(1 row)

编辑:

这是第二种更短的方法(也就是说,您不需要 array_agg_custom_cut 函数,但正如您所见,查询中需要额外的 ARRAY 级别):

CREATE AGGREGATE array_agg_custom(anyarray)
(
SFUNC = array_cat,
STYPE = anyarray
);

SELECT
array_agg_custom(
ARRAY[
ARRAY[
alert_type::text,
id::text,
CAST(extract(epoch FROM date_happened) AS text)
]
])
FROM e;

结果:

              array_agg_custom              
--------------------------------------------
{{red,1,1305036906},{yellow,2,1308787279}}
(1 row)

关于postgresql - 数组类型的 array_agg,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6782268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com