假设我有一个具有以下结构的表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中最快的方法是什么?
答案 0 :(得分:3)
您需要将数组的所有元素转换为行才能对其求和:
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;