PostgreSQL 添加两个整数数组
PostgreSQL adding two integer Arrays
我有两个 integer[]
类型的实例(由 Timescale histogram
函数生成),例如{3,5,1}
和 {2,2,2}
.
我想将这两个数组添加到 {5,7,3}
但使用
SELECT "ID", histogram(...) + histogram(...)
FROM "ID"
GROUP BY "ID"
抛出以下错误:operator does not exist: integer[] + integer[]
。有什么办法可以做到这一点?
我觉得没有这个功能
为了实现您的目标(在 SQL 中),您必须取消嵌套数组,然后添加相应的元素并将结果聚合回数组。
SELECT
array_agg(
COALESCE(h1.val, 0)+COALESCE(h2.val, 0)
ORDER BY COALESCE(h1.row_number, h2.row_number)
) as result
FROM
(SELECT ROW_NUMBER() over (), val FROM unnest('{3,5,1,5}'::int[]) as val) as h1
FULL JOIN (SELECT ROW_NUMBER() over (), val FROM unnest('{2,2,2}'::int[]) as val) as h2 ON h1.row_number=h2.row_number
我正在使用 ROW_NUMBER window 函数来获取数组元素编号。
FULL JOIN 是必需的,因为数组的长度可能不同。这也是为什么添加元素时需要COALESCE的原因。
多亏了@a_horse_with_no_name,可以使用序数重写查询而不依赖 row_number() 函数:
SELECT
array_agg(
COALESCE(h1.val, 0)+COALESCE(h2.val, 0)
ORDER BY COALESCE(h1.no, h2.no)
) as result
FROM
unnest('{3,5,1,5}'::int[]) WITH ORDINALITY as h1(val, no)
FULL JOIN unnest('{2,2,2}'::int[]) WITH ORDINALITY as h2(val, no) ON h1.no=h2.no
我有两个 integer[]
类型的实例(由 Timescale histogram
函数生成),例如{3,5,1}
和 {2,2,2}
.
我想将这两个数组添加到 {5,7,3}
但使用
SELECT "ID", histogram(...) + histogram(...)
FROM "ID"
GROUP BY "ID"
抛出以下错误:operator does not exist: integer[] + integer[]
。有什么办法可以做到这一点?
我觉得没有这个功能
为了实现您的目标(在 SQL 中),您必须取消嵌套数组,然后添加相应的元素并将结果聚合回数组。
SELECT
array_agg(
COALESCE(h1.val, 0)+COALESCE(h2.val, 0)
ORDER BY COALESCE(h1.row_number, h2.row_number)
) as result
FROM
(SELECT ROW_NUMBER() over (), val FROM unnest('{3,5,1,5}'::int[]) as val) as h1
FULL JOIN (SELECT ROW_NUMBER() over (), val FROM unnest('{2,2,2}'::int[]) as val) as h2 ON h1.row_number=h2.row_number
我正在使用 ROW_NUMBER window 函数来获取数组元素编号。 FULL JOIN 是必需的,因为数组的长度可能不同。这也是为什么添加元素时需要COALESCE的原因。
多亏了@a_horse_with_no_name,可以使用序数重写查询而不依赖 row_number() 函数:
SELECT
array_agg(
COALESCE(h1.val, 0)+COALESCE(h2.val, 0)
ORDER BY COALESCE(h1.no, h2.no)
) as result
FROM
unnest('{3,5,1,5}'::int[]) WITH ORDINALITY as h1(val, no)
FULL JOIN unnest('{2,2,2}'::int[]) WITH ORDINALITY as h2(val, no) ON h1.no=h2.no