假设我有一个具有以下结构的表 my_table
:
id::int counts::array
--------------------
02 {0,0,0,0,0,0,0}
03 {10,0,0,20,40,10,0}
04 {0,0,0,0,0,0,0}
05 {0,20,30,20,0,10,10}
06 {0,0,0,27,0,50,4}
07 {1,0,0,0,0,0,0}
08 {0,0,0,0,0,0,0}
我想运行以下查询,以伪代码形式呈现:
SELECT id, counts FROM my_table
WHERE NOT SUM(ARRAY_TO_STRING(counts, ', ')::int) = 0
我知道我不能在 where 子句中使用聚合函数,但在 PSQL 中执行此操作的最快方法是什么?
最佳答案
您需要将数组的所有元素变成行才能对它们求和:
select mt.id, mt.counts
from my_table mt
where (select sum(i) from unnest(mt.counts) as t(i)) <> 0;
您可以创建函数以简化操作:
create function int_array_sum(p_array int[])
returns bigint
as
$$
select sum(i) from unnest(p_array) as t(i);
$$
language sql;
然后你可以使用:
select mt.id, mt.counts
from my_table mt
where int_array_sum(mt.counts) <> 0;
关于sql - 在 where 子句中使用数组函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54750669/