[英]PostgreSQL count array values
What I would like is to count the array elements which corresponds to true (attendance), false (non-attendance) and NULL for any single event. 我想要的是计算对应于真(出勤),假(非出勤)和任何单个事件的NULL的数组元素。
EDIT: 编辑:
I just realized that arrays do not behave as I thought in pSQL, so a simple 我刚刚意识到数组的行为与我在pSQL中的行为不同,所以很简单
userconfirm bool[]
Might suffice. 可能就够了。 However, I am still having the same problem counting true/false/null values.
但是,我仍然在计算true / false / null值时遇到同样的问题。 I will attempt to edit the question below to match this new constraint.
我将尝试编辑下面的问题以匹配此新约束。 I apologize for any errors.
我为任何错误道歉。
I have a column such as 我有一个专栏如
userconfirm bool[]
Where userconfirm[314] = true
would mean that user #314 will attend. userconfirm[314] = true
表示用户#314将参加。 (false = no attend, NULL = not read/etc). (false =没有参加,NULL =没有阅读/等)。
I'm not sure this is the best solution for this functionality (users announce their attendance to an event), but I am having trouble with an aggregate function on this column. 我不确定这是否是此功能的最佳解决方案(用户宣布他们参加活动),但我在此专栏上遇到了聚合功能问题。
select count(*) from foo where id = 6 AND true = ANY (userconfirm);
This only returns 1, and trying to google "counting arrays" does not turn up anything useful. 这只返回1,并试图谷歌“计数数组”没有出现任何有用的东西。
How would I go about counting the different values for a single event? 我如何计算单个事件的不同值?
You can use unnest
in your SELECT like this: 您可以在SELECT中使用
unnest
,如下所示:
select whatever,
(select sum(case b when 't' then 1 else 0 end) from unnest(userconfirm) as dt(b))
from your_table
-- ...
For example, given this: 例如,鉴于此:
=> select * from bools;
id | bits
----+--------------
1 | {t,t,f}
2 | {t,f}
3 | {f,f}
4 | {t,t,t}
5 | {f,t,t,NULL}
You'd get this: 你会得到这个:
=> 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
If that's too ugly, you could write a function: 如果那太难看了,你可以编写一个函数:
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;
and use it to pretty up your query: 并用它来完成你的查询:
=> select id, count_trues_in(bits) as trues from bools;
id | trues
----+-------
1 | 2
2 | 1
3 | 0
4 | 3
5 | 2
你可以使用array_length函数结果:
SELECT SUM(array_length(userconfirm, 2)) WHERE id = 6;
This one may do the trick( unnest ). 这一个可以做的伎俩( UNNEST )。
postgres=# with y(res) as (
postgres(# with x(a) as (
postgres(# values (ARRAY[true,true,false])
postgres(# union all
postgres(# values (ARRAY[true,null,false])
postgres(# )
postgres(# select unnest(a) as res
postgres(# from x
postgres(# )
postgres-# select count(*)
postgres-# from y
postgres-# where res;
count
-------
3
(1 row)
postgres=#
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.