微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

PostgreSQL计数数组值

我想要的是计算对应于真(出勤),假(非出勤)和任何单个事件的NULL的数组元素.

编辑:

我刚刚意识到数组的行为与我在psql中的行为不同,所以很简单

userconfirm bool[]

可能就够了.但是,我仍然在计算true / false / null值时遇到同样的问题.我将尝试编辑下面的问题以匹配此新约束.我为任何错误道歉.

我有一个专栏如

userconfirm bool[]

userconfirm [314] = true表示用户#314将参加. (false =没有参加,NULL =没有阅读/等).

我不确定这是否是此功能的最佳解决方案(用户宣布他们参加活动),但我在此专栏上遇到了聚合功能问题.

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

这只返回1,并试图谷歌“计数数组”没有出现任何有用的东西.

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

解决方法

您可以在SELECT中使用 unnest,如下所示:

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}
  5 | {f,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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐