gpt4 book ai didi

sql - PostgreSQL 计数数组值

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

我想要计算任何单个事件对应于 true(出席)、false(未出席)和 NULL 的数组元素。

编辑:

我刚刚意识到数组在 pSQL 中的行为并不像我想的那样,所以一个简单的

userconfirm bool[]

可能就足够了。但是,我在计算真/假/空值时仍然遇到同样的问题。我将尝试编辑下面的问题以匹配这个新约束。对于任何错误,我深表歉意。


我有一列,例如

userconfirm bool[]

userconfirm[314] = true 表示用户 #314 将参加。 (false = 不参加,NULL = 未读/等)。

我不确定这是此功能的最佳解决方案(用户宣布他们参加事件),但我在使用此列的聚合函数时遇到了问题。

select count(*) from foo where id = 6 AND true = ANY (userconfirm);

这只会返回 1,并且尝试用 google 搜索“counting arrays”并没有找到任何有用的东西。

我将如何计算单个事件的不同值?

最佳答案

您可以使用 unnest在你的 SELECT 中是这样的:

select whatever,
(select sum(case b when 't' then 1 else 0 end) from unnest(userconfirm) as dt(b))
from your_table
-- ...

例如,给定这个:

=> select * from bools;
id | bits
----+--------------
1 | {t,t,f}
2 | {t,f}
3 | {f,f}
4 | {t,t,t}
5 | {f,t,t,NULL}

你会得到这个:

=> select id, (select sum(case b when 't' then 1 else 0 end) from unnest(bits) as dt(b)) as trues from bools;
id | trues
----+-------
1 | 2
2 | 1
3 | 0
4 | 3
5 | 2

如果那太难看,你可以写一个函数:

create function count_trues_in(boolean[]) returns bigint as $$
select sum(case b when 't' then 1 else 0 end)
from unnest($1) as dt(b)
$$ language sql;

并用它来完善您的查询:

=> select id, count_trues_in(bits) as trues from bools;
id | trues
----+-------
1 | 2
2 | 1
3 | 0
4 | 3
5 | 2

关于sql - PostgreSQL 计数数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9143882/

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