sql - 在 where 子句中使用数组函数

标签 sql arrays postgresql

假设我有一个具有以下结构的表 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/

相关文章:

mysql - 中间表多值查找

sql - 如果表列为空,则查询添加默认值

postgresql - 2 个 Postgres 实例的不同结果

postgresql - OCaml:将数据序列化为具有附加要求的字符串

sql - 正则表达式删除字符串中所有出现的多个字符

sql - 为什么我不能在 count(*) "column"中使用别名并在having 子句中引用它?

mysql - SQL - 如何根据两个表获取总和?

c - c中表格内的不同颜色

c - 从未知大小列表填充 C 中的锯齿状 char 数组

PHP 和 MySQL - 使用数组填充选择下拉列表